Home >Java >javaTutorial >How to count the number of words in a string in java
如何统计字符串中的单词数?
这道题呢?主要针对的是英文字符串的情况。虽然中文字符串中也可以有空白字符,但不存在单词这一说。
public class CountNumberOfWordsInString { public static void main(String[] args) { countNumberOfWords("My name is Wanger"); countNumberOfWords("I Love Java Programming"); countNumberOfWords(" Java is very important "); } private static void countNumberOfWords(String line) { String trimmedLine = line.trim(); int count = trimmedLine.isEmpty() ? 0 : trimmedLine.split("\\s+").length; System.out.println(count); } }
输出结果如下所示:
4 4 4
split() 方法可以对字符串进行拆分,参数不仅可以是空格,也可以使正则表达式代替的空白字符(多个空格、制表符);返回的是一个数组,通过 length 就可以获得单词的个数了。
The above is the detailed content of How to count the number of words in a string in java. For more information, please follow other related articles on the PHP Chinese website!