IAm*_*aja 0 java regex string text word-count
给出以下字符串:
字符串文字="树林是\nlovely,\ t\t\t深刻而深刻.";
我希望将所有空格视为单个字符.所以例如,\n
1个字符.该\t\t
也应该是1个字符.有了这个逻辑,我算了36个字符和7个字.但是当我通过以下代码运行时:
String text = "The woods are\nlovely,\t\tdark and deep.";
int numNewCharacters = 0;
for(int i=0; i < text.length(); i++)
if(!Character.isWhitespace(text.charAt(i)))
numNewCharacters++;
int numNewWords = text.split("\\s").length;
// Prints "30"
System.out.println("Chars:" + numNewCharacters);
// Prints "8"
System.out.println("Words:" + numNewWords);
Run Code Online (Sandbox Code Playgroud)
它告诉我有30个字符和8个单词.任何想法为什么?提前致谢.