【发布时间】:2019-10-02 17:41:02
【问题描述】:
我正在尝试找出输入字符串中的总字符数。当我输入字符串(一个句子)时,它只计算字符串第一个单词中的字符总数。我需要它来计算字符总数。我知道有很多方法可以做到这一点。但这是我的入门课程,也是我可以使用它的唯一方法 string.length();方法。
这就是我所拥有的:
String shortSentence;
System.out.println("Please input a short sentence, with a period at the end.");
shortSentence = keyboardReader.next();
String length = shortSentence.length();
System.out.println("The total characters in the sentence is " + length);
【问题讨论】:
-
而 string.length() 为您提供字符总数....
-
使用 nextLine 代替 next
-
不,当我为shortSentence输入一个字符串时,比如“hey there.”,它只读取字符串中“hey”的总共3个字符,我需要它来计算总数整个字符串中的字符数。所以一共应该是10个字符,包括空格
-
正如我所说,您正在使用 next() 并获取字符直到遇到空格,使用 nextLine() 来抓取整行。所以不要
shortSentence = keyboardReader.next();做shortSentence = keyboardReader.nextLine(); -
抱歉,在您发布评论之前发布了评论。它在其中起作用!太感谢了。几乎所有我要讲的都是我课堂讲座的幻灯片,其中的示例没有显示 nextLine(),只是 next()。谢谢!
标签: java string character counting