考虑以下字符串:为什么我的角色和单词会被忽略?
字符串文本= “树林是\ nlovely,\ t \ tdark和深”;
我希望所有的空格都作为单个字符来处理。例如,\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个单词。任何想法为什么?提前致谢。
打印出您在第一个循环中找到的每个非空白字符,以及拆分数组的所有元素 - 它应该非常明显。如果不是,请用你发现的内容编辑你的问题,我们可以帮助你。 – Floris 2013-03-03 23:12:40