我正在尝试编写一个java程序,该程序将计算声明句子中的单词数,然后将句子分解为单词,以便列出具有数值的单词并显示单词。我已经解决了总数,但我似乎无法分解句子中的单词,然后按时间顺序列出它们。我可以用字符来完成,但不能用文字来完成。
我已经探索了 Java Cookbook 和其他地方来寻找解决方案,但我只是不太理解它。正如我所说,我可以计算字符数,也可以计算单词数,但无法将各个单词打印在单独的行上,并在字符串中计算它们的计数值。
public class MySentenceCounter {
public static void main(String[] args) {
String sentence = "This is my sentence and it is not great";
String[] wordArray = sentence.trim().split("\\s+");
int wordCount = wordArray.length;
for (int i=0; i < sentence.length( ); i++)
System.out.println("Char " + i + " is " + sentence.charAt(i));
//this produces the character count but I need it to form words, not individual characters.
System.out.println("Total is " + wordCount + " words.");
}
}
预期结果应如下所示:
1 This
2 is
3 my
4 sentence
5 and
6 it
7 is
8 not
9 great
Total is 9 words.
最佳答案
迭代您创建的 wordArray
变量,而不是 for 循环中的原始 sentence
字符串:
public class MySentenceCounter {
public static void main(String[] args) {
String sentence = "This is my sentence and it is not great";
String[] wordArray = sentence.trim().split("\\s+");
// String[] wordArray = sentence.split(" "); This would work fine for your example sentence
int wordCount = wordArray.length;
for (int i = 0; i < wordCount; i++) {
int wordNumber = i + 1;
System.out.println(wordNumber + " " + wordArray[i]);
}
System.out.println("Total is " + wordCount + " words.");
}
}
输出:
1 This
2 is
3 my
4 sentence
5 and
6 it
7 is
8 not
9 great
Total is 9 words.
关于java - 有没有办法 println 来枚举和列出字符串中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942276/