gpt4 book ai didi

java - 计算 StdIn 中的行数和字符数

转载 作者:行者123 更新时间:2023-12-01 10:39:25 24 4
gpt4 key购买 nike

我想在运行此代码时将一些内容放入 StdIn 中,例如一行文本。该代码应打印出文本字符串中的行数、字符数和单词数。我目前能够计算出字符和单词的数量,但在查找行数时遇到困难。我如何在这里实现它?

public class WordCount
{
public static void main(String [] args){
int words = 0, lines = 0, characters = 0;
while (!StdIn.isEmpty()) {
String word = StdIn.readString();
characters += word.length();
words++;
}
StdOut.println("There are " + words + "words");
StdOut.println("There are " + characters + "characters");
}
}

最佳答案

来自doc ,您可以使用方法 readLine() 而不是 readString()。这样您就可以轻松获得行数。得到该行后,您可以将其按空格分割并计算单词数。循环遍历每个单词以获得字符数。

public class WordCount
{
public static void main(String [] args){
int words = 0, lines = 0, characters = 0;
while (!StdIn.isEmpty()) {
String line = StdIn.readLine();
lines++;
String[] lineWords = line.split("\\s+");
words += lineWords.length;
for(String word : lineWords)
characters += word.length();
}
StdOut.println("There are " + lines + "lines");
StdOut.println("There are " + words + "words");
StdOut.println("There are " + characters + "characters");
}
}

关于java - 计算 StdIn 中的行数和字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34504036/

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