简体   繁体   English

Java初学者 - 计算句子中的单词数

[英]Java Beginner - Counting number of words in sentence

I am suppose to use methods in order to count number of words in the a sentence. 我想使用方法来计算句子中的单词数量。 I wrote this code and I am not quite sure why it doesn't work. 我写了这段代码,我不太清楚为什么它不起作用。 No matter what I write, I only receive a count of 1 word. 无论我写什么,我只收到一个字数。 If you could tell me how to fix what I wrote rather than give me a completely different idea that would be great: 如果你能告诉我如何解决我写的东西,而不是给我一个完全不同的想法,那将是伟大的:

import java.util.Scanner;

public class P5_7 
{
    public static int countWords(String str)
    {
        int count = 1;
        for (int i=0;i<=str.length()-1;i++)
        {
            if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
            {
                count++;
            }
        }
        return count;
    }
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence = in.next();
        System.out.print("Your sentence has " + countWords(sentence) + " words.");
    }
}

An easy way to solve this problem: 解决此问题的简便方法:

return str.split(" ").length;

Or to be more careful, this is how you'd take into account more than one whitespace: 或者为了更加小心,这就是你如何考虑多个空白:

return str.split("\\s+").length;

You need to read entire line. 你需要阅读整行。 Instead of in.next(); 而不是in.next(); use in.nextLine() . 使用in.nextLine()

Try This Simple Code with split() and argument as spaces 尝试使用split()和参数作为空格的这个简单代码

int length=str.split(" ").length;

It will return number of words in your sentence. 它将返回句子中的单词数。

Should you not have int count = 0; 如果你没有int count = 0; instead of int count = 1; 而不是int count = 1; , in case of blank sentences. ,如果是空白句子。 If you're getting Java errors please could you add them to your question. 如果您遇到Java错误,请将它们添加到您的问题中。

i<=str.length()-1应该是i<str.length()-1或者你将在str.charAt(i+1)得到一个IndexOutOfBoundsException(可用的值是str.charAt(0)str.charAt(str.length()-1) )。

Please check for boundary conditions at str.charAt(i+1) . 请检查str.charAt(i+1)边界条件。 It can result in a StringIndexOutOfBoundsException when the string is terminated by a space. 当字符串以空格终止时,它可能导致StringIndexOutOfBoundsException

  1. Account for cases where the string starts with a ' ' 考虑字符串以''开头的情况
  2. The String could be blank. 字符串可以是空白的。
  3. The definition of a 'word' could differ. “单词”的定义可能有所不同。 For example - '1 2'. 例如 - '1 2'。 Are 1,2 words ? 是1,2个字吗?

I know you do not want an alternate method but string.split(" ").length() is an easier way to start. 我知道你不想要一个替代方法,但string.split(“”)。length()是一种更容易的方法。

Actually, if you enter a sentence like: 实际上,如果你输入一句话:

"Hello World"

your code String sentence = in.next(); 你的代码String sentence = in.next(); will only get the first word in the sentence ie, Hello . 只会得到句子中的第一个单词,即Hello So, you need to use in.nextLine() in place of in.next() to get the whole sentence ie, Hello World . 因此,您需要使用in.nextLine()代替in.nextLine() in.next()来获取整个句子,即Hello World

This is how i have done it : 这就是我做到的方式:

It works fine too 它也可以正常工作

    import java.util.Scanner;


    public class countwords {

        public static void main(String args[]){
            Scanner in=new Scanner(System.in);
            System.out.println("Enter your sentence:[Try to ignore space at end]");
            String s=in.nextLine();
            System.out.println("Size of the string is "+s.length());
            int res=count(s);
            System.out.println("No of words in the given String --->>"+"  "+s+" "+"is"+" :"+res);
        }


        private static int count(String s) {
            // TODO Auto-generated method stub
            int count=0;
            if(s.charAt(0)!=' '){
                count++;
            }
            for(int i=0;i<s.length();i++){
                if((s.charAt(i)==' ')){
                    count++;
                }
            }
            return count;
        }


}

OUTPUT: this is my world bonaza 输出:这是我的世界bonaza

Size of the string is 23 字符串的大小是23

No of words in the given String --->> this is my world bonazais :5 给定字符串中没有单词--- >>这是我的世界bonazais:5

There are some bugs try to correct them and repost 有一些错误尝试纠正它们并重新发布

A more simple way that i found was : 我发现一种更简单的方法是:

Just use this : 只要用这个:

    // Read a string
String st=s.nextLine();

// Split string with space
String words[]=st.trim().split(" ");
This program works fine, 

step1:input the string step1:输入字符串

step2:split the string into single word store in a arrays step2:将字符串拆分为数组中的单个字存储

step3 :return the length of the arrays step3:返回数组的长度

public class P5_7 
{
public static int countWords(String str)
{
   String words[]=str.split(" ");
   int count=words.length;
    return count;
}
public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a sentence: ");
    String sentence =in.nextLine();
    System.out.print("Your sentence has " + countWords(sentence) + " words.");
}

} }

Tested method - handles all inputs 经过测试的方法 - 处理所有输入

public static void countwords() {
    String s = "  t    ";
    int count = 0;
    int length = s.length()-1;
    char prev = ' ';

    for(int i=length; i>=0; i--) {
        char c = s.charAt(i);
        if(c != prev && prev == ' ') {
            count++;
        }
        prev = c;
    }
    System.out.println(count);
}

The simple logic is count the spaces only if there aren't any white spaces before. 简单的逻辑是只有在之前没有任何空格的情况下才计算空格。 Try this: 尝试这个:

public class WordCount 
{
    public static void main(String[] args) 
    {
        int word=1;
        Scanner s = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String str=s.nextLine();
        for(int i=1;i<str.length();i++)
            {
                if(str.charAt(i)==' ' && str.charAt(i-1)!=' ')
                word++;
            }
       System.out.println("Total Number of words= "+word);
    }
}

import java.util.HashMap; import java.util.HashMap;

import java.util.Map; import java.util.Map;

import java.util.Scanner; import java.util.Scanner;

public class WordrCount { 公共类WordrCount {

public static void main(final String[] args) {
    System.out.println("Please Enter Your String: ");
    final Map<String, Integer> hm = new HashMap<String, Integer>();
    final Scanner sc = new Scanner(System.in);
    final String s1 = sc.nextLine();
    final String[] c1 = s1.split(" ");
    for (int i = 0; i < c1.length; i++) {
        if (!hm.containsKey(c1[i])) {
            hm.put(c1[i], (Integer)1);
        }// if
        else {
            hm.put(c1[i], hm.get(c1[i]) +(Integer) 1);

        }// else
    }// for

    System.out.println("The Total No Of Words: " + hm);

}// main

}// WordCount }// 字数

I'd suggest to use BreakIterator . 我建议使用BreakIterator This is the best way to cover not standard languages like Japanese where there aren't spaces that separates words. 这是覆盖日语等标准语言的最佳方式,因为没有空格可以分隔单词。

Example of word counting here . 这里字数统计的例子。

Here is one more method just using split , trim , equals methods to improve code and performance. 这是另一种方法,只需使用splittrimequals方法来改进代码和性能。

This code will work with space as well. 此代码也适用于空间。

public int countWords(String string){
    String strArr [] = string.split("\\s");
    int count = 0;
    for (String str: strArr) {
        if(!str.trim().equals("")){
            count++;
        }
    }
    return count;
}

Use this method to calculate the number of words in a String:- 使用此方法计算字符串中的单词数: -

    private int calculateWords(String s){

    int count=0;

    if(s.charAt(0)!=' ' || s.charAt(0)!=','){

        count++;

    }

    for(int i=1;i<s.length();i++){
            if((s.trim().charAt(i)==' ' && s.charAt(i+1)!=' ')  || (s.trim().charAt(i)==',' && s.charAt(i+1)!=',')){

                count++;
            }

    }

    return count;
}
class Words {
public static void main(String[] args) {

    String str="Hello World this is new";
    str=str.trim();
    int n=str.length();
    char a[]=new char[n];
    str.getChars(1,n,a,0);
    for (int i=0;i<str.length() ; i++){
        if(a[i]==' ') count++;
    }
    System.out.println("No. of words = "+(count+1));
}

} }

package test;
public class CommonWords {
    public static void main(String[] args) {
        String words = "1 2 3 44 55                            966 5                                   88              ";
        int count = 0;
        String[] data = words.split(" ");
        for (String string : data) {
            if (!string.equals("")) {
                count++;
            }
        }
        System.out.println(count);
    }
}

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

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