how to count the exact number of words in a string that has empty spaces between words?

前端 未结 9 1766
猫巷女王i
猫巷女王i 2020-12-03 14:35

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

相关标签:
9条回答
  • 2020-12-03 15:35

    http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

    Splits this string around matches of the given regular expression.

    0 讨论(0)
  • 2020-12-03 15:37
    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)==' '){
                        i++;
                        break;
                    }
                }
            }
        }
        return counter;
    }
    

    This is what you need if don't use the predefined function. I have tested it by myself. Please let me know if there is any bugs!

    0 讨论(0)
  • 2020-12-03 15:37

    My few solutions:

    public static int wordcount1(String word) {
    
            if (word == null || word.trim().length() == 0) {
                return 0;
            }
    
            int counter = 1;
    
            for (char c : word.trim().toCharArray()) {
                if (c == ' ') {
                    counter++;
                }
            }
            return counter;
        }
    

    //

    public static int wordcount2(String word) {
            if (word != null || word.length() > 0) {
                return word.trim().length()
                        - word.trim().replaceAll("[ ]", "").length() + 1;
            } else {
                return 0;
            }
        }
    

    // Recursive

    public static int wordcount3(String word) {
            if (word == null || word.length() == 0) {
                return 0;
            }
            if (word.charAt(0) == ' ') {
                return 1 + wordcount3(word.substring(1));
            }
            return wordcount3(word.substring(1));
        }
    

    //

    public static int wordcount4(String word) {
            if (word == null || word.length() == 0) {
                return 0;
            }
    
            String check = word.trim();
            int counter = 1;
            for (int i = 0; i < check.length(); i++) {
                if (i > 0 && Character.isSpaceChar(check.charAt(i))
                        && !Character.isSpaceChar(check.charAt(i - 1))) {
                    counter++;
                }
            }
            return counter;
        }
    
    0 讨论(0)
提交回复
热议问题