简体   繁体   English

字数统计 Java

[英]Word count on Java

How can I count the words of a sentence given as string?如何计算作为字符串给出的句子的单词数? We are allowed to use only the following: for loops, if statemant, while , charAt , length() .我们只能使用以下内容: for循环、 if statemant、 whilecharAtlength()

I wrote this code:我写了这段代码:

public static int getWordCount()
{
  String data = "bla bla bla bla";
  int Count = 0;
  for (int i=0; i<data.length(); i++)
  {
    if (data.charAt(i) != ' ')
    Count ++;
  }
  return Count;
}

But it counts only the letters and not the words.但它只计算字母而不计算单词。

Here's a suggestion: Count the number of ' ' and add 1? 这是一个建议:计算' '的数量并加1?

Example: 例:

"bla bla bla bla"
    1   2   3      : 3 + 1   = 4

"hello"
                   : 0 + 1   = 1

If you want to get fancy you could keep a boolean variable named something like lastWasSpace , set it to true when running into a space, setting it to false when you run into a non-space character. 如果你想得到想象,你可以保留一个名为lastWasSpace的布尔变量,在运行到空间时将其设置为true,当遇到非空格字符时将其设置为false。 If you only increment the Count when lastWasSpace is false, you'll be able to handle strings with multiple consecutive spaces as well. 如果只在lastWasSpace为false时递增Count ,那么你也可以处理多个连续空格的字符串。

             "bla    bla      bla"
                 1      2             : 2 + 1 = 3
lastWasSpace: FFFFTTTFFFFTTTTTFFFF

the given code would indeed count letters and not words. 给定的代码确实会计算字母而不是单词。 You may want to change the condition to: 您可能希望将条件更改为:

if (data.charAt(i) == ' ')

this means, if you find a space, this would mark the beginning of the next word. 这意味着,如果找到空格,这将标记下一个单词的开头。 Also, the last word will not be counted so you should return Count+1 instead of Count . 此外,最后一个单词不会被计算,所以你应该返回Count+1而不是Count

There are several assumptions I made here: 我在这里做了几个假设:

  1. There will be exactly one space in between words. 单词之间只有一个空格。
  2. There will not be any leading or trailing spaces. 不会有任何前导或尾随空格。

To consider multiple spaces between words, you would need to modify the code a little. 要考虑单词之间的多个空格,您需要稍微修改一下代码。 Instead of checking if a character is space, check to see if a character is non-space and the previous character was either a space or no character for the case of first word. 不是检查字符是否是空格,而是检查字符是否为非空格,而前一个字符对于第一个单词的情况是空格还是无字符。 This would also handle leading and trailing spaces. 这也可以处理前导和尾随空格。

String ss =  "   leading spaces in string  ";
String[] sa = ss.trim().split("\\w+");
System.out.println(sa.length);

Note the use of trim to handle surrounding whitespace. 注意使用trim来处理周围的空白。

public class Main {

    public static void main(String[] args) {
        String data = "This is a Test";
        int wordCount = 1;
        int charCount = 0;
        for (int i = 0; i < data.length(); i++) {
            if (data.charAt(i) == ' ') {
                wordCount++;
            } else {
                charCount++;

            }
        }
        System.out.println("wordCount = " + wordCount);
        System.out.println("charCount = " + charCount);
    }
}

My solution: 我的解决方案

public static int getWordCount() {
  String data = "bla bla bla bla";
  String[] arr = data.split(" ");
  return arr.length;
}

Use the below code for count the words in the line, 使用以下代码计算行中的单词,

            int index = 0;
            int numWords =0;
            boolean prevwhitespace = true;
            String line = "bla bla bla bla";
            while(index < line.length())
            {
                char c = line.charAt(index++);
                boolean currwhitespace = Character.isWhitespace(c);
                if(prevwhitespace && !currwhitespace)
                {
                    numWords++;
                }
                prevwhitespace= currwhitespace;
            }
           System.out.println("no. of words in the line :: " +numWords);
String s = "Aljohani Abdallah";
int counter = 1;
for (int i = 0; i < s.length() - 1; i++) {
    if (s.charAt(i) == ' ' && s.charAt(i + 1) != ' ')
        counter++;
}
if (s == " ")
    counter = 0;
System.out.println(counter);

this code above here is count number of words in String so the first thing I have to know is length of the string and then we do if condition, if i was in index equals space at the same time must the letter after space not equal space the add 1 to counter上面的这段代码是计算字符串中的单词数所以我首先要知道的是字符串的长度然后我们做如果条件,如果我同时在索引等于空间必须空间后的字母不等于空间计数器加 1

the end if the String was empty the counter should be zero.最后,如果字符串为空,则计数器应为零。

String str = "  Hello there   my name     is   Bill    ";
str = str.trim();
int count = 0;
for(int i = 0; i<str.length(); i++) {
    if(str.charAt(i) == ' ' && str.charAt(i-1) != ' ') {
        count++;
    }
}

System.out.println(count+1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM