【问题标题】:Count words in my string with special characters java用特殊字符java计算我的字符串中的单词
【发布时间】:2021-05-10 01:28:31
【问题描述】:

字符串中总共有 51 个单词,但是我的代码返回给我 56 个单词,我不明白为什么。

public class PartB

{ // 实例变量 - 用你自己的替换下面的例子

public static int countWords(String str) 
{ 
      
    // Check if the string is null 
    // or empty then return zero 
    if (str == null || str.isEmpty()) 
        return 0; 
      
    // Splitting the string around 
    // matches of the given regular 
    // expression 
    String[] words = str.split("[\\s+,'/]"); 
      
    // Return number of words 
    // in the given string 
    return words.length; 
} 

public static void main(String args[]) 
{ 
      
    // Given String str 
    String str = "Sing, sing a song/Let the world sing along/" +
    "Sing of love there could be/Sing for you and for me/" +
    "Sing, sing a song/Make it simple to last/" +
    "Your whole life long/Don't worry that it's not/" +
    "Good enough for anyone/Else to hear/" +
    "Just sing, sing a song";
     
      
    // Print the result 
    System.out.println("No of words : " + 
       countWords(str)); 
} 

}

【问题讨论】:

  • 检查words(通过设置断点或记录它)并找出不应该存在的单词。
  • 在调试中投入一些精力。但是提示 - 您在 split 函数的参数中提供的模式不正确,因此在某些情况下它会计算多个单词。

标签: java string counting


【解决方案1】:

您的[\s+,'/] 正则表达式中有两个错误:

  • + 加号应该在[ ] 字符类之外。

    原因:如果没有 +,文本 "Sing, sing" 将有 2 个分隔符,一个逗号和一个空格,它们之间有一个空标记,而您计算的是那个空标记。

  • ' 撇号不应该在那里。

    原因:使用 ',文本 Don't 将是 2 个单词,而不是 1 个。

所以正则表达式应该是:[\s,/]+

只改变对split("[\\s,/]+")的拆分调用,结果变为:

No of words : 51

【讨论】:

    猜你喜欢
    • 2015-03-03
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2020-08-13
    • 2020-02-29
    相关资源
    最近更新 更多