如何在一个单独的行中逐字显示句子

Ins*_*ane 5 java text-segmentation

句子字符串应该是由空格分隔的一堆单词,例如"现在是时间".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);
    }

}
Run Code Online (Sandbox Code Playgroud)

nhg*_*rif 0

Java 的String类有一个replace你应该研究的方法。这将使这个homework很容易。

字符串替换