Java打印字符串作为数组输入,每个字符串都在新行上

时间:2018-01-24 15:47:04

标签: java

我需要按照程序输出在新行上输入每个单词的字符串并计算总单词数。到目前为止,每个字母都在新行上输出。我使用text.split对单词进行计数并尝试将其添加到for循环中,但它不会起作用,可能是因为for循环是Integer但我无法找到如何添加它。

public class TextTest {

    public static void main(String[] args) {
        String text = Input.getString("Text: ");
        String[] separated = text.split(" ");//separates by spaces 

        do {
            if (text.isEmpty()) {
                System.out.println("empty text");
            } else {
                for (Integer position = 0; position < text.length(); position++) {

                    System.out.println(text.charAt(position));
                }
            }
            int WordCount = separated.length;
            System.out.println("number of words: " + WordCount);
        } while (Repeat.repeat());

5 个答案:

答案 0 :(得分:3)

select
REGEXP_SUBSTR(REGEXP_REPLACE('mobile Motorola Nexus 6','(\d)','\1'),'[^ ]+',1,1) A,
REGEXP_SUBSTR(REGEXP_REPLACE('mobile Motorola Nexus 6','(\d)','\1'),'[^ ]+',1,2) B,
REGEXP_SUBSTR(REGEXP_REPLACE('mobile Motorola Nexus 6','(\d)','\1'),'[^ ]+',1,3) C
from dual;

A      B        C
------ -------- ------
mobile Motorola Nexus6

答案 1 :(得分:3)

public static void main(String[] args) {
        String text = "THIS IS A SAMPLE TEXT";
        String[] separated = text.split(" ");//separates by spaces 

            if (text.isEmpty()) {
                System.out.println("empty text");
            } else {
                for (Integer position = 0; position < separated.length; position++) {

                    System.out.println(separated[position]);
                }
            }
            int WordCount = separated.length;
            System.out.println("number of words: " + WordCount);
    }

您的代码不起作用,因为您使用文本输出单词而不是您创建的新数组并将其中的单词分开。这可以工作,因为每个单词都位于新创建的数组中的索引中。希望我帮忙!

答案 2 :(得分:3)

使用Lambdas,这将简单如下:

public static void main(String[] args) {
    String text = "THIS IS A SAMPLE TEXT";
    String[] splitted = text.split(" ");

    System.out.println("Number of words: " + Stream.of(splitted).count());
    Stream.of(splitted).forEach(System.out::println);
}

答案 3 :(得分:2)

您可以更改for,如下所示

String[] splits = text.split("\\s+"); // split by one or more spaces.
for (String split: splits){
    System.out.println(split);
}
System.out.println("Word Count: " + splits.length);

单词的数量将被分割计数。此外,您不需要考虑空分割,因为RegExp将处理单词被多个空格分隔的情况。

答案 4 :(得分:1)

使用Java 8流,这样做。它

String text = "THIS IS A SAMPLE TEXT";
long count = Stream.of(text.split("\\s+")) // split based on whitespace
        .peek(System.out::println) // print each one
        .count(); // count them
System.out.println("Word count: " + count); // print the count