Java怎么获取字符串单词个数

其他教程   发布日期:2023年07月21日   浏览次数:207

今天小编给大家分享一下Java怎么获取字符串单词个数的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

    Java获取字符串单词个数

     public static int getWordCount(String content){
            int count = 0;
            String cn_words = content.replaceAll("[^(u4e00-u9fa5,。《》?;'‘:“”【】、)(……¥!・)]", "");
            int cn_words_count = cn_words.length();
            String non_cn_words = content.replaceAll("[^(a-zA-Z0-9`-=';.,/~!@#$%^&*()_+|}{":><?[])]", " ");
            int non_cn_words_count = 0;
            String[] temp = non_cn_words.split(" ");
            for(String ch:temp){
                if(ch.trim().length() != 0) non_cn_words_count++;
            }
            count = cn_words_count + non_cn_words_count;
            return count;
        }
        public static void main(String[] args) {
    		System.out.println(getWordCount("我爱你 zhanglulu _")); // 输出5,单词是以空格分开,所以这里我爱你三个字加一个单词zhanglulu和一个下划线,空格不算。
    	}

    统计String单词数的三种方法

    统计字符串里包含有多少个单词,这是Java代码常用的场景。介绍三种简单的方法来对其进行统计。这里所谓的单词,是指连续的非空字符串。如“Hello”则为一个词,“I love Guangzhou”则为三个词。

    方法一:使用split

    在类String中,有split()这个方法,可以将字符进行分割。可以通过对字符串以空白字符进行分割,则可以得到结果。

    public int countWithSplit(String str) {
        if (Strings.isNullOrEmpty(str)) {
            return 0;
        }
        return str.split("s+").length;
    }

    代码中"s+"为正则表达式,表示所有的空白字符。

    方法二:使用StringTokenizer

    public int countWithStringTokenizer(String str) {
        if (Strings.isNullOrEmpty(str)) {
            return 0;
        }
        StringTokenizer tokenizer = new StringTokenizer(str);
        return tokenizer.countTokens();
    }

    StringTokenizer是一个很有用的类,构造函数有三个:

    • 1. StringTokenizer(String str) :构造一个用来解析 str 的 StringTokenizer 对象。java 默认的分隔符是空格("")、制表符( )、换行符( )、回车符( )。

    • 2. StringTokenizer(String str, String delim) :构造一个用来解析 str 的 StringTokenizer 对象,并提供一个指定的分隔符。

    • 3. StringTokenizer(String str, String delim, boolean returnDelims) :构造一个用来解析 str 的 StringTokenizer 对象,并提供一个指定的分隔符,同时,指定是否返回分隔符。

    方法三:使用原始的char判断

    public int countWithChar(String str) {
        if (Strings.isNullOrEmpty(str)) {
            return 0;
        }
        int wordCount = 0;
        boolean isWord = false;
        int endOfLine = str.length() - 1;
        char[] chars = str.toCharArray();
     
        for (int i = 0; i < chars.length; i++) {
            // 如果是非空字符, word = true.
            if (isWord(chars[i]) && i != endOfLine) {
                isWord = true;
     
                // 非空字符后遇到空字符,则数量加1
            } else if (!isWord(chars[i]) && isWord) {
                wordCount++;
                isWord = false;
                // 非空字符后遇到行尾
            } else if (isWord(chars[i]) && i == endOfLine) {
                wordCount++;
            }
        }
        return wordCount;
    }
     
    private boolean isWord(char c) {
        return c != ' '
                && c != '	'
                && c != '
    '
                && c != '
    '
                && c != 'f';
    }

    测试代码

    简单写了几个测试用例,测试通过。

    public class CountWordTest {
        private CountWord countWord = new CountWord();
     
        @Test
        public void test() {
            testStringCount(null, 0);
            testStringCount("", 0);
            testStringCount(" ", 0);
            testStringCount(" 	
    f", 0);
            testStringCount("0", 1);
            testStringCount("abcdef", 1);
            testStringCount("a b c", 3);
            testStringCount("a,b,c", 1);
            testStringCount("a
    b
    c", 3);
            testStringCount("a,b	
    c", 2);
        }
     
        private void testStringCount(String str, int expectedCount) {
            assertEquals(expectedCount, countWord.countWithSplit(str));
            assertEquals(expectedCount, countWord.countWithStringTokenizer(str));
            assertEquals(expectedCount, countWord.countWithChar(str));
        }
    }

    这三种方法都非常简单,没有什么技术难点,用到了String、StringTokenizer、正则、Guava、JUnit等,非常基础。

    以上就是Java怎么获取字符串单词个数的详细内容,更多关于Java怎么获取字符串单词个数的资料请关注九品源码其它相关文章!