【问题标题】:How to find the total amount of characters in w string?如何查找字符串中的字符总数?
【发布时间】: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


【解决方案1】:

使用nextLine()

shortSentence = keyboardReader.nextLine();

将长度转换为字符串:

String length = Integer.toString(shortSentence.length()); 

【讨论】:

    【解决方案2】:
    public class Test {
    
    public static void main(String[] args) throws IOException {
    
        System.out.println("Please input a short sentence, with a period at the end.");
        InputStreamReader r=new InputStreamReader(System.in);  
        BufferedReader br=new BufferedReader(r);   
        String shortSentence=br.readLine();  
    
        System.out.println(shortSentence.length());
    
    }
    

    }

    这使我输出为 11,输入为“hello world”。看看这是否有帮助。

    【讨论】:

    • 如果您能解释原始代码做错了什么,这将是一个更好的答案。
    猜你喜欢
    • 2017-03-22
    • 2022-12-16
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多