Counting the number of a certain letter appears in

2020-05-03 10:50发布

问题:

I have an ArrayList that stores notes (strings) in the form of "do the dishes". I have a notes class with a method that is supposed to go through all the notes in the ArrayList and count the number of times a certain letter appears. This is the method I have written so far:

public int countNumberOf(String letter) {
        int count = 0;
        for (int i = 0; i < notes.size(); i++) {
            String note = (notes.get(i));
            for (int j = 0; i < note.length(); i++) {
                String letterTemp = note.substring(i, i);
                if (letterTemp.equalsIgnoreCase(letter)) {
                    count++;
                }
            }

        }
        return count;
    }

However, when I run the program, I'm getting zero for the number of times the letter "a" appears even though I know it's present in the ArrayList. What am I doing wrong?

回答1:

Instead of passing a String to a method and doing a substring, you can always access and compare the characters, e.g.:

public int countNumberOf(char letter) {
...
String letterTemp = note.charAt(i);
if (letter == letterTemp) {
        count++;
}

Another example:

public static int countOccurrences(String text, char character) {
    int count = 0;
    for (int i = 0; i < text.length(); i++) {
        if (text.charAt(i) == character) {
            count++;
        }
    }
    return count;
}


回答2:

note.substring(i, i) will always return an empty string, so letterTemp.equalsIgnoreCase(letter) will always return false. You should use note.substring(i, i+letter.length())

Although I suggest that you use char for comparison, in this kind of task. Mostly for simplicity's sake, and to avoid unecessary intermediate strings. The logic would be the same



回答3:

Your second for-loop seems incorrect.

for (int i = 0; i < notes.size(); i++) {
    String note = (notes.get(i));
    for (int j = 0; i < note.length(); i++) {

Watch out for those index variables i and j.



回答4:

How about:

int countOfLetter = note.length() - (note.replace(letter,"")).length();