java如何统计一个字符串中有多少个单词呢?
下文讲述java中统计字符串中单词个数的方法分享,如下所示:
统计字符串中单词个数
实现思路: 依次遍历字符串中字符的个数,然后判断是否为一个单词 当是单词时,则单词个数加1例:
统计字符串中单词个数
public static int countWords(String s){ int wordCount = 0; boolean word = false; int endOfLine = s.length() - 1; for (int i = 0; i < s.length(); i++) { // if the char is a letter, word = true. if (Character.isLetter(s.charAt(i)) && i != endOfLine) { word = true; // if char isn't a letter and there have been letters before, // counter goes up. } else if (!Character.isLetter(s.charAt(i)) && word) { wordCount++; word = false; // last word of String; if it doesn't end with a non letter, it // wouldn't count without this. } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) { wordCount++; } } return wordCount; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。