java - 仅打印以 pre Java 开头的单词

标签 java arrays arraylist

创建一个 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/

相关文章:

javascript - 如何从 React Native 中的两个数组中提取不相同的元素?

java - 读写包含 Parcelable 对象的 ArrayList 的 ArrayList 以传递 Intent

java - 根据对象中的变量对对象数组列表进行排序

Javascript 计算具有点符号的对象的键

java - Spring 单元测试

java - 它是一种测试 JUnit 函数内部抛出的异常的方法吗?

java - KeyListener 和 boolean 值不起作用

python - 了解 numpy.where 的运行时和等效替代方案

android - 在 Arraylist 的 ListView 的列表项上显示值

java - 如何在 JPanel 上覆盖、调整大小和居中组件?