给定以下字符串:
String text = "树林\n可爱,\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);
它告诉我有 30 个字符和 8 个单词。关于为什么的任何想法?提前致谢。