验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

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

阅读:812 来源:乙速云 作者:代码code

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`\-=';.,/~!@#$%^&*()_+|}{":>

      统计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 默认的分隔符是空格("")、制表符(t)、换行符(n)、回车符(r)。

      • 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 != 't'
                  && c != 'n'
                  && c != 'r'
                  && c != 'f';
      }

      测试代码

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

      public class CountWordTest {
          private CountWord countWord = new CountWord();
       
          @Test
          public void test() {
              testStringCount(null, 0);
              testStringCount("", 0);
              testStringCount(" ", 0);
              testStringCount(" trnf", 0);
              testStringCount("0", 1);
              testStringCount("abcdef", 1);
              testStringCount("a b c", 3);
              testStringCount("a,b,c", 1);
              testStringCount("arbnc", 3);
              testStringCount("a,btnc", 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等,非常基础。

    分享到:
    *特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
    相关文章
    {{ v.title }}
    {{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
    你可能感兴趣
    推荐阅读 更多>