Java 打印这句话中的每个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35515851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:45:54  来源:igfitidea点击:

Print each word from this sentence

javawordsentence

提问by Lauren?iu Ro?u

I have the following sentence:

我有以下句子:

This is a text and we should print each word

I want to print each word from this sentence.

我想打印这句话中的每个单词。

package lab2_3;

public  class Main {

    public static void main(String[] args) {

        String s2 = "This is a text and we should print each word";


        int i;
        int j;
        for (i = 0; i <= s2.length() - 1; i++){
            if (s2.substring(i).startsWith(" ") || i == 0){

                //here I search for the start of the sentence or " "
                for (j = i + 1; j <= s2.length() - 1; j++){

                    if (s2.substring(j).startsWith(" ") || j == s2.length() - 1) {
                        //here I search for the next " " or the end of the sentence
                        System.out.println(s2.substring(i, j));
                        //printing
                        i = j;
                        //i=j because the next search must be done from where we left

                    }
                }
            }
        }
    }
}

Output:

输出:

This
 is
 a
 text
 and
 we
 should
 print
 each
 wor

As you can see it almost works, but the letter d is missing from the last word. A possible solution is to add " " at the end and it will work, but I don't want to do that.

如您所见,它几乎可以正常工作,但是最后一个单词中缺少字母 d。一个可能的解决方案是在最后添加“”,它会起作用,但我不想这样做。

Can you please tell me where it is my mistake and how to fix it ?

你能告诉我我的错误在哪里以及如何解决吗?

Also, can you please provide a better solution for this.

另外,您能否为此提供更好的解决方案。

采纳答案by Pshemo

You are overcomplicating things. String already have split(regexDelimiter)method which accepts regex representing place on which you want to split.

你把事情复杂化了。字符串已经有split(regexDelimiter)方法接受正则表达式来表示要拆分的位置。

Also enhanced for loopallows us to easily iterate over all elements of array or implementations of Iterable interface

增强的 for 循环使我们可以轻松地遍历数组的所有元素或 Iterable 接口的实现

for (String str : strArray){
   //do something with str
}

Since Java 8 we have also String.join(delimiter, elements)method which can create string representing element0[delimiter]element1[delimiter]...

从 Java 8 开始,我们还有String.join(delimiter, elements)方法可以创建表示element0[delimiter]element1[delimiter]...

So depending what you are looking for you may want to use

因此,根据您正在寻找的内容,您可能想要使用

for (String word : s2.split(" ")){
    System.out.println(word);
}

or

或者

String inEachLine = String.join(System.lineSeparator(), s2.split(" "));

or maybe even simpler

或者甚至更简单

String inEachLine = s2.replace(" ", System.lineSeparator()); 

Last example simply creates new String based on original one, This new string will have replaced each space with OS dependant line separator (like for Windows \r\n).

最后一个示例只是基于原始字符串创建新字符串,这个新字符串将用操作系统相关的行分隔符替换每个空格(如 Windows \r\n)。



You can also use additional class designed to help us reading data from string. This class is Scanner. So in your case you could simply use

您还可以使用额外的类来帮助我们从字符串中读取数据。这个类是Scanner. 所以在你的情况下,你可以简单地使用

Scanner sc = new Scanner(s2);
while(sc.hasNext()){
    System.out.println(sc.next());
}

回答by NullPointerException

You can split the string in array

您可以拆分数组中的字符串

String s2 = "This is a text and we should print each word";

    String [] s3 = s2.split(" ");
    int i;
    for (i = 0; i < s3.length; i++)
      System.out.println(s3[i]);

 }

If you don't want to hard code for space you can use a regex

如果您不想对空间进行硬编码,则可以使用正则表达式

String s2 = "This is a text and we should print each word";

    String [] s3 = s2.split("\s");
    int i;
    for (i = 0; i < s3.length; i++)
    System.out.println(s3[i]);

}

Output

输出

This
is
a
text
and
we
should
print
each
word

回答by Blake Yarbrough

  1. Declare the String
  2. Split the string into an array using the split()method on the Stringobject
  3. Loop over each element in the array and print it to the screen
  1. 声明 String
  2. 使用对象split()上的方法将字符串拆分为数组String
  3. 遍历数组中的每个元素并将其打印到屏幕上


public static void main(String[] args) {
    String slashString = "This is a text and we should print each word";

    for(String word : slashString.split(" ")){
        System.out.println(word);
    }
}

Output:

输出:

This
is
a
text
and
we
should
print
each
word

回答by saka1029

Try this.

尝试这个。

    String s2 = "This is a text and we should print each word";
    String[] t = s2.split("(?= )");
    for (String e : t)
        System.out.println(e);

result

结果

This
 is
 a
 text
 and
 we
 should
 print
 each
 word