为什么我的角色和字数很重要?

IAm*_*aja 0 java regex string text word-count

给出以下字符串:

字符串文字="树林是\nlovely,\ t\t\t深刻而深刻.";

我希望将所有空格视为单个字符.所以例如,\n1个字符.该\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个单词.任何想法为什么?提前致谢.

Rei*_*eus 5

您正在匹配各个空格.相反,你可以匹配一个或多个:

text.split("\\s+")
Run Code Online (Sandbox Code Playgroud)