我想计算字符串内容的字数和行数。 这是我的代码:
private int[] getLineAndWordCount(final String textContent) {
int wordCount = 0;
int lineCount = 0;
if (textContent.length() > 0) {
textContent = textContent.replace("\t", " ");
String[] newLineArrays = textContent.split("\n");
lineCount = newLineArrays.length;
for (String newLineStr : newLineArrays) {
String[] wordsArray = newLineStr.trim().split(" ");
for (String word : wordsArray) {
if (word.length() > 0) {
wordCount++;
}
}
}
}
return new int[]{lineCount, wordCount};
}
这段代码工作正常,但在执行过程中它会创建很多子字符串。那么有没有其他有效的方法来做同样的事情呢?谢谢。
最佳答案
尝试使用java.util.Scanner
。例如:
Scanner textScanner = new Scanner(text);
while (textScanner.hasNextLine()) {
linesCount++;
Scanner wordsScanner = new Scanner(textScanner.nextLine());
while (wordsScanner.hasNext()) {
wordsCount++;
wordsScanner.next();
}
}
java.util.Scanner
的 javadoc:http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
关于java - 计算字符串中的行数和单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21423088/