gpt4 book ai didi

Java 将字符串中的单词打印到数组中

转载 作者:行者123 更新时间:2023-11-30 03:34:21 26 4
gpt4 key购买 nike

我想获取用户通过缓冲阅读器输入的任何单词的输入,并将它们放入一个数组中。然后我想在单独的行上打印出每个单词。所以我知道我需要某种单词计数器来计算用户输入的单词数。这就是我到目前为止所拥有的。

import java.text.*;
import java.io.*;

public class test {
public static void main (String [] args) throws IOException {

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValue;

inputValue = input.readLine();
String[] words = inputValue.split("\\s+");

假设用户输入单词这里是测试运行。程序应该计算 5 个值并打印出单词

here
is
a
test
run

对于如何解决这个问题有任何帮助或建议吗?

最佳答案

确实没有必要计算单词数(除非你真的想这样做)。您可以改为使用 for-each loop喜欢

String[] words = inputValue.split("\\s+");
for (String word : words) {
System.out.println(word);
}

正如我所说,如果您真的想要,那么您可以获得 length数组(您的“计数”),然后使用常规 for 循环,例如

String[] words = inputValue.split("\\s+");
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}

如果您不需要将每个单词放在单独的行上,那么您也可以使用 Arrays.toString(Object[])和类似的东西

String[] words = inputValue.split("\\s+");
System.out.println(Arrays.toString(words));

关于Java 将字符串中的单词打印到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28334303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com