java—尝试在不同的行上打印字符串中的单词

q8l4jmvw  于 2021-07-08  发布在  Java
关注(0)|答案(7)|浏览(352)

我想让它把每个单词打印在自己的行上。

String movie = "10 Things I Hate About You";
String g = "";
for (int letter = 0; letter < movie.length(); letter++) {
    if (letter != ' ') {
        g += word.charAt(letter);
    } else {
        g += "\n";
    }
}
System.out.println(g);

但是,每次我都会被抛出这个错误。

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8
    at java.lang.String.charAt(String.java:658)
    at MyProgram.main(MyProgram.java:34)
qyuhtwio

qyuhtwio1#

String movie = "10 Things I Hate About You";
StringBuilder g = new StringBuilder();
String g = "";
for(int letter = 0; letter < movie.length(); letter++) {
    if(word.charAt(letter) != ' ') {
        g.append(word.charAt(letter));
    }
    else {
        g.append("\n");
    }
}System.out.println(g);
sauutmhj

sauutmhj2#

一条带有lambda的线:

System.out.print(
    Stream.of( movie.split( " " ) ).collect( Collectors.joining( "\n" ) )
 );
``` `joining(…)` 在内部与 `java.util.StringJoiner` …一个遵循原作的羔羊 `char` 由 `char` 方法:

movie.codePoints().forEach( c
-> System.out.print( c == ' ' ? '\n' : (char)c ) );

toe95027

toe950273#

这是一个做同样的事情一行。

System.out.println(movie.replaceAll(" ", "\n"));
fhity93d

fhity93d4#

你能用吗 String.replace(char,char) 方法:

String movie = "Lorem ipsum dolor sit amet";
String mov = movie.replace(' ', '\n');
System.out.println(mov);

输出:

Lorem
ipsum
dolor
sit
amet
pbwdgjma

pbwdgjma5#

你应该检查一下 movie.charAt(letter) != ' ' 如果是呢 true ,您应该添加 movie.charAt(letter)g .

public class Main {
    public static void main(String[] args) {
        String movie = "10 Things I Hate About You";
        String g = "";
        for (int letter = 0; letter < movie.length(); letter++) {
            if (movie.charAt(letter) != ' ') {
                g += movie.charAt(letter);
            } else {
                g += "\n";
            }
        }
        System.out.println(g);
    }
}

输出:

10
Things
I
Hate
About
You

更简单的解决方案:

public class Main {
    public static void main(String[] args) {
        String movie = "10 Things I Hate About You";
        movie = movie.replace(' ', '\n');
        System.out.println(movie);
    }
}

输出:

10
Things
I
Hate
About
You
drkbr07n

drkbr07n6#

可以使用正则表达式拆分数组。不需要循环来检查单个字符。这将使用与正在使用的操作系统相关的行分隔符。

String movie = "10 Things I Hate About You";
movie = movie.replaceAll(" ", System.getProperty("line.separator"));

System.out.println(movie);
jhkqcmku

jhkqcmku7#

可以将字符串拆分为一个数组,并在新行中打印该数组的每个元素。

String movie = "One word per line";
String[] arrOfStr = movie.split(" ");
for(String s : arrOfStr){
    System.out.println(s);
}

相关问题