How do I count the number of words in a string?

后端 未结 8 1601
感情败类
感情败类 2021-01-13 02:54

I need to count the number of words and I am assuming the correct way to do it is by calculating the number of times that the previous character in a string is not a letter

相关标签:
8条回答
  • 2021-01-13 03:35
       if (string.charAt(i-1) == alphabets.charAt(j)) {
           counter++;
       }
    

    You are incrementing the counter if the character is some alphabet character. You should increment it if it is no alphabet character.

    0 讨论(0)
  • 2021-01-13 03:40

    Your suggestion to use a regex like "[A-Za-z]" would work fine. In a split command, you'd split on the inverse, like:

    String[] words = "Example test: one, two, three".split("[^A-Za-z]+");

    EDIT: If you're just looking for raw speed, this'll do the job more quickly.

    public static int countWords(String str) {
        char[] sentence = str.toCharArray();
        boolean inWord = false;
        int wordCt = 0;
        for (char c : sentence) {
            if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
                if (!inWord) {
                    wordCt++;
                    inWord = true;
                }
            } else {
                inWord = false;
            }
        }
        return wordCt;
    }
    
    0 讨论(0)
提交回复
热议问题