【发布时间】:2013-02-17 23:31:28
【问题描述】:
给定以下字符串:
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 个单词。关于为什么的任何想法?提前致谢。
【问题讨论】:
-
打印出你在第一个循环中找到的每个非空白字符,以及拆分数组的所有元素——那时应该很明显了。如果不是,请使用您找到的内容编辑您的问题,我们可以为您提供帮助。
标签: java regex string text word-count