Home > Java > javaTutorial > How to count the number of words in a string in java

How to count the number of words in a string in java

WBOY
Release: 2023-04-27 23:34:05
forward
2383 people have browsed it

如何统计字符串中的单词数?

这道题呢?主要针对的是英文字符串的情况。虽然中文字符串中也可以有空白字符,但不存在单词这一说。

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);     } }
Copy after login

输出结果如下所示:

4 4 4
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template