【问题标题】:how to count the letters in each letter in a string in Java? [closed]如何计算Java中字符串中每个字母中的字母? [关闭]
【发布时间】:2013-03-10 01:06:02
【问题描述】:

我已使用此代码进行了尝试:

String st="Hello world have a nice day";
String arr=st.Split(" ");
for (int i=0; i < arr.length; i++) {
    ???
}

但它不起作用。

我希望它输出如下内容:

Hello=5
World=5
have=4
a=1
nice=4
day=3

请问有人知道正确的密码吗?

【问题讨论】:

    标签: java count split words


    【解决方案1】:

    你可以这样使用:

    String[] words = yourString.split(" ");
    
    for (String word : words) {
      System.out.println(word + " length is: " + word.length());
    }
    

    【讨论】:

      【解决方案2】:

      word.length() 返回字符串的长度。

      但是,split() 方法只会用空格分割字符串,而将所有内容留在结果分割中。我的意思是标点符号、制表符、换行符等,所有这些都将计入长度。因此,您可能想要执行以下操作,而不是仅仅执行word.length()

      word.replaceAll("\p{Punct}", "").trim().length().

      • replaceAll("\p{Punct}", "") 删除所有标点符号 字符串。

      • trim() 删除所有前导和尾随空格。

      例如,一个句子:

      我看到了一个鬼火。\n

      \n 表示行尾字符,例如,如果您从文件中读取字符串,则可能会得到该字符)。

      句子将拆分为:

      "I"  
      "saw"  
      "a"  
      "will-o'-the-wisp.\n"
      

      最后一个字符串

      将-o'-the-wisp。\n

      有 18 个字符,但这超过了单词中的字符数。在replaceAll() 方法之后,字符串将如下所示:

      willothewisp\n

      trim() 方法之后,字符串将如下所示:

      小精灵

      长度为12,即单词的长度。

      【讨论】:

        【解决方案3】:

        使用增强的 for 循环并打印出单词及其长度。

        foreach(String w : st.split()) {
            System.out.println(w + ": " + w.length());
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-08
          • 2012-06-04
          • 2023-03-19
          • 2023-02-24
          • 1970-01-01
          • 2019-06-04
          • 1970-01-01
          相关资源
          最近更新 更多