简体   繁体   中英

Java determining if each character in a string is a letter

I'm using isLetter() and charAt() to see if a character in str is a letter or not. The use of this method is to find the number of words in a string that are at least the minimum word length. I don't want it to count anything other than letters. (im a java noob)

public static int wordCount(String str, int minLength) {     
//Method that counts words.

    int count = 0;
    boolean isLetter = false;
    for (int i = 0, wordLength = 0; i < str.length() + 1; i++) {
        isLetter = Character.isLetter(str.charAt(i)); //Why doesn't this line work?
        if (i == str.length() || str.charAt(i) == ' ' || isLetter==false) { 
            if (wordLength >= minLength) {              
                count++;                                                
            }
            wordLength = 0;                                 
        } else {                                                            
            wordLength++;                                       
        }
    }
    return count;
}

The problem is in your for loop. You have it iterate until i < str.length() + 1 . That means at some point, you will be asking for str.charAct(str.length()) . Because Java arrays (and Strings) index from 0, the index is too high and will break.

Instead, just have your for loop iterate until i < str.length() . That should fix it.

It's not the Character.isLetter not working, it's the str.charAt(i) that throws an exception when i reaches str.length() .

Your loop iterates i from 0 to str.length() , inclusive - a total of str.length()+1 characters. The call of charAt(i) when i is str.length() would be illegal.

To fix this problem, remove + 1 from the expression in the for loop, or make sure that str.charAt(i) is not called when i is equal to str.length() . For example, you could use the short-circuiting feature like this:

for (int i = 0, wordLength = 0; i < str.length() + 1; i++) {
    if (i == str.length() || !Character.isLetter(str.charAt(i))) {
        ...
    }
}

Above, str.charAt(i) is not called when i == str.length() , preventing the crash ( demo ).

You may want to change a few more things:

  • str.charAt(i) == ' ' || isLetter==false str.charAt(i) == ' ' || isLetter==false can be reduced to isLetter==false or even to !isLetter , because space character is not a letter
  • The declaration of isLetter can be moved inside the loop, and combined with initialization (unless you decide to get rid of the variable altogether using the code snipped shown above).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM