计数字符串中包含特殊字符java的单词



字符串中总共有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)); 
} 

}

您的[s+,'/]regex有两个错误:

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

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

  • 不应该有'撇号。

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

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

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

No of words : 51

最新更新