【发布时间】: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 函数的参数中提供的模式不正确,因此在某些情况下它会计算多个单词。