Java 如何在一行中逐字显示句子

Java 如何在一行中逐字显示句子,java,text-segmentation,Java,Text Segmentation,句子字符串应该是由空格分隔的一串单词,例如“现在就是时间”。 showWords的工作是每行输出一个句子的单词 这是我的家庭作业,我正在努力,你可以从下面的代码中看到。我不知道如何以及使用哪个循环逐字输出。。。请帮忙 import java.util.Scanner; public class test { public static void main(String[] args) { Scanner in = new Scanner(System.in);

句子字符串应该是由空格分隔的一串单词,例如“现在就是时间”。 showWords的工作是每行输出一个句子的单词

这是我的家庭作业,我正在努力,你可以从下面的代码中看到。我不知道如何以及使用哪个循环逐字输出。。。请帮忙

import java.util.Scanner;


public class test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter the sentence");
        String sentence = in.nextLine();

        showWords(sentence);
}

    public static void showWords(String sentence) {
        int space = sentence.indexOf(" ");
        sentence = sentence.substring(0,space) + "\n" + sentence.substring(space+1);
        System.out.println(sentence);
    }

}

Java的
String
类有一个
replace
方法,您应该研究它。这将使这个
作业
相当容易


由于这是一个家庭作业问题,我不会给出确切的代码,但我想让您看看
字符串
-类中的
拆分方法。然后我会推荐一个for循环


另一种方法是替换字符串中的空格,直到没有多余的空格为止(这可以使用循环和不使用循环来完成,具体取决于您的操作方式)

更新

使用String类的split方法在空格字符分隔符上分割输入字符串,从而得到一个单词字符串数组

然后使用修改后的for循环遍历该数组,以打印数组的每个项

import java.util.Scanner;


    public class Test {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);

            System.out.println("Enter the sentence");
            String sentence = in.nextLine();

            showWords(sentence);
    }

        public static void showWords(String sentence) {
            String[] words = sentence.split(' ');
            for(String word : words) {
             System.out.println(word);
            }
        }

    }

使用regex可以使用一行程序:

System.out.println(sentence.replaceAll("\\s+", "\n"));
还有一个额外的好处,就是多个空格不会留下空白行作为输出。
如果您需要更简单的
String
方法,您可以使用
split()
作为

String[] split = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (String word : split) {
    if (word.length() > 0) { // eliminate blank lines
        sb.append(word).append("\n");
    }
}
System.out.println(sb);

如果您需要一种更简单的方法(下至
String
索引)以及更多关于您自己代码行的方法;您需要将代码包装在一个循环中,并对其进行一些调整

int space, word = 0;
StringBuilder sb = new StringBuilder();

while ((space = sentence.indexOf(" ", word)) != -1) {
    if (space != word) { // eliminate consecutive spaces
      sb.append(sentence.substring(word, space)).append("\n");
    }
    word = space + 1;
}

// append the last word
sb.append(sentence.substring(word));

System.out.println(sb);

你走对了路。你的showWords方法适用于第一个单词,你只需要完成它,直到没有单词为止

通过它们循环,最好使用while循环。如果使用while循环,请考虑何时需要停止,也就是当没有更多单词时


为此,您可以保留最后一个单词的索引并从那里进行搜索(直到没有更多),或者删除最后一个单词,直到句子字符串为空

这个问题是关于家庭作业的。发布一个直截了当的答案并没有特别大的帮助。这个问题是关于家庭作业的。发布一个直接的答案并没有特别大的帮助。
replace
方法将通过一个方法调用处理所有出现的空格字符。不需要循环。@nhgrif该方法是,但还有其他替代方法(如replaceFirst,或使用OP似乎已经尝试过的子字符串)<代码>替换
当然可能是最简单的解决方案。多个空格怎么样?正则表达式替换是一种更好的方法choice@Bohemian我会让OP来决定。这个决定不是我做的。你也可以把中间的两个空格想象成“长度为零的单词”。“长度为零的单词”…很好的反驳:)