如何计算单词之间空格为空格的字符串中的确切单词数? [英] how to count the exact number of words in a string that has empty spaces between words?

查看:204
本文介绍了如何计算单词之间空格为空格的字符串中的确切单词数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个名为wordCount的方法,该方法接受String作为其参数,并返回String中的单词数。单词是一个或多个非空格字符的序列(除''之外的任何字符)。例如,调用wordCount(hello)应返回1,调用wordCount(你好吗?)应返回3,调用wordCount(此字符串有宽空格)应返回5,并调用wordCount ()应该返回0.

Write a method called wordCount that accepts a String as its parameter and returns the number of words in the String. A word is a sequence of one or more nonspace characters (any character other than ' '). For example, the call wordCount("hello") should return 1, the call wordCount("how are you?") should return 3, the call wordCount(" this string has wide spaces ") should return 5, and the call wordCount(" ") should return 0.

我做了一个函数:

public static int wordCount(String s){

  int counter = 0;

  for(int i=0; i<=s.length()-1; i++) {

    if(Character.isLetter(s.charAt(i))){

      counter++;

      for(i<=s.length()-1; i++){

        if(s.charAt(i)==' '){

          counter++;
        }
      }                
    }
  }

  return counter;
}

但我知道这有1个限制,它也会计算空格数在字符串中的所有单词都已完成之后,它还将计算2个空格,因为可能是2个单词:(
是否有预定义的字数统计功能?或者可以更正此代码吗?

But i know this has 1 limitation that it will also count the number of spaces after all the words in the string have finished nad it will also count 2 blank spaces as possibly being 2 words :( Is there a predefined function for word count? or can this code be corrected?

推荐答案

如果你想忽略前导,尾随和重复的空格你可以使用

If you want to ignore leading, trailing and duplicate spaces you can use

String trimmed = text.trim();
int words = trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;

这篇关于如何计算单词之间空格为空格的字符串中的确切单词数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆