Java Beginner - Counting number of words in sentence

后端 未结 17 1669
忘了有多久
忘了有多久 2021-01-01 05:29

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 on

相关标签:
17条回答
  • 2021-01-01 05:53

    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);
    }
    
    0 讨论(0)
  • 2021-01-01 05:54

    Should you not have int count = 0; instead of int count = 1;, in case of blank sentences. If you're getting Java errors please could you add them to your question.

    0 讨论(0)
  • 2021-01-01 05:57

    Actually, if you enter a sentence like:

    "Hello World"
    

    your code String sentence = in.next(); will only get the first word in the sentence i.e., Hello. So, you need to use in.nextLine() in place of in.next() to get the whole sentence i.e., Hello World.

    0 讨论(0)
  • 2021-01-01 05:57

    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;
    }
    
    0 讨论(0)
  • 2021-01-01 06:00

    I'd suggest to use 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.

    0 讨论(0)
  • 2021-01-01 06:00

    Here is one more method just using split, trim, equals methods to improve code and performance.

    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;
    }
    
    0 讨论(0)
提交回复
热议问题