用特殊字符计算我的字符串中的单词数 java

Count words in my string with special characters java

字符串中总共有 51 个单词,但是我的代码 returns 给我 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)); 
} 

}

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

  • +加号应该在[ ]字符外 class.

    原因: 如果没有 +,文本 "Sing, sing" 将有 2 个分隔符,一个逗号和一个 space,以及一个空标记在它们之间,您正在计算那个空令牌。

  • ' 撇号不应该出现。

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

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

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

No of words : 51