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

前端 未结 9 1765
猫巷女王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:21

    Simply use s.split(" ").length and for wide spaces...use s.trim().replaceAll("\\s+"," ").split(" ").length

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

    It should be easy with:

    String[] arr = "how are you sir".split("\\s");
    System.out.printf("Count [%d]%n", arr.length);
    
    0 讨论(0)
  • 2020-12-03 15:25

    If you want to ignore leading, trailing and duplicate spaces you can use

    String trimmed = text.trim();
    int words = trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
    
    0 讨论(0)
  • 2020-12-03 15:26
    public static int wordCount(String s){
        if (s == null)
           return 0;
        return s.trim().split("\\s+").length;
    }
    

    Have fun with the function.

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

    Added some lines to your code:

    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)==' '){
                                        counter++;
                                        i++;
                                        while (s.charAt(i)==' ')
                                            i++;
                                        }
                                }
    
                        }
    
    
                }
                return counter;
       }
    
    0 讨论(0)
  • 2020-12-03 15:33
    String str="I am a good boy";
    String[] words=str.split("\\s+");
    System.out.println(words.length);
    
    0 讨论(0)
提交回复
热议问题