繁体   English   中英

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

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

我想使用方法来计算句子中的单词数量。 我写了这段代码,我不太清楚为什么它不起作用。 无论我写什么,我只收到一个字数。 如果你能告诉我如何解决我写的东西,而不是给我一个完全不同的想法,那将是伟大的:

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.");
    }
}

解决此问题的简便方法:

return str.split(" ").length;

或者为了更加小心,这就是你如何考虑多个空白:

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

你需要阅读整行。 而不是in.next(); 使用in.nextLine()

尝试使用split()和参数作为空格的这个简单代码

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

它将返回句子中的单词数。

如果你没有int count = 0; 而不是int count = 1; ,如果是空白句子。 如果您遇到Java错误,请将它们添加到您的问题中。

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

请检查str.charAt(i+1)边界条件。 当字符串以空格终止时,它可能导致StringIndexOutOfBoundsException

  1. 考虑字符串以''开头的情况
  2. 字符串可以是空白的。
  3. “单词”的定义可能有所不同。 例如 - '1 2'。 是1,2个字吗?

我知道你不想要一个替代方法,但string.split(“”)。length()是一种更容易的方法。

实际上,如果你输入一句话:

"Hello World"

你的代码String sentence = in.next(); 只会得到句子中的第一个单词,即Hello 因此,您需要使用in.nextLine()代替in.nextLine() in.next()来获取整个句子,即Hello World

这就是我做到的方式:

它也可以正常工作

    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;
        }


}

输出:这是我的世界bonaza

字符串的大小是23

给定字符串中没有单词--- >>这是我的世界bonazais:5

有一些错误尝试纠正它们并重新发布

我发现一种更简单的方法是:

只要用这个:

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

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

step1:输入字符串

step2:将字符串拆分为数组中的单个字存储

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.");
}

}

经过测试的方法 - 处理所有输入

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);
}

简单的逻辑是只有在之前没有任何空格的情况下才计算空格。 尝试这个:

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.Map;

import java.util.Scanner;

公共类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

}// 字数

我建议使用BreakIterator 这是覆盖日语等标准语言的最佳方式,因为没有空格可以分隔单词。

这里字数统计的例子。

这是另一种方法,只需使用splittrimequals方法来改进代码和性能。

此代码也适用于空间。

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

使用此方法计算字符串中的单词数: -

    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