创建一个 StringDemo 类,其中包含以下静态方法: • 一种方法,接收一个句子,使用单个空格对其进行标记,然后仅打印以“pre”开头的单词。 • 在main 方法中声明2 个变量并将它们初始化为您选择的句子;然后使用这 2 个句子测试您在上一步中定义的方法。
我的尝试
import java.util.ArrayList;
public class StringDemo{
public static void main(String... args){
String S1 = "We love prefix that have car strongly wheels and car
seats";
String S2 = "I have a lovely designed car that has many car features
beautifully and the car has a good car";
printWordsWithPre(S1);
printWordsWithPre(S2);
System.out.println(printWordsWithPre(S1));
System.out.println(printWordsWithPre(S1));
}
//- Tokenises a string/sentence and prints only the words that end with
ly.
public static void printWordsWithPre(String str){
String[] sTokens = str.split("\\p{javaWhitespace}");
for(int i = 0; i < sTokens.length; i++){
if(sTokens[i].endsWith("pre")){
System.out.println(sTokens[i]);
}
}
}
最佳答案
尝试以下代码:
import java.util.ArrayList;
public class StringDemo{
public static void main(String... args){
String S1 = "We love prefix that have car strongly wheels and car seats";
String S2 = "I have a lovely designed car that has many beautifully predesigned car features and the car has a good prebuilt car";
printWordsWithPre(S1);
printWordsWithPre(S2);
// These functions don't return any data so they can't be printed. The results are already printed in the function above.
/*System.out.println(printWordsWithPre(S1));
System.out.println(printWordsWithPre(S1));*/
}
// Tokenises a string/sentence and prints only the words that starts with pre.
public static void printWordsWithPre(String str){
String[] sTokens = str.split("\\p{javaWhitespace}");
for(int i = 0; i < sTokens.length; i++){
//check if it starts with rather than ends with
if(sTokens[i].startsWith("pre")){
System.out.println(sTokens[i]);
}
}
}
}
我进行了以下更改:
- 添加了一些以 pre 开头的单词;
- 删除了 System.out.println 的 主要是因为他们试图打印无效的返回;
- 改变了结尾 开始于。
关于java - 仅打印以 pre Java 开头的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49782443/