Skip to content
Advertisement

Java Looking for specific letters in a sting

I was wondering how to iterate over a string and to check how many hi’s come out

For example, if the string is “hihi” the count should output 2.

This is what I have so far

public static int countHi(String str) {
    int counter = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.substring(i, i + 1) == "h") {
            if (str.substring(i, i + 1) == "i") {
                counter = counter + 1;
            }
        }
    }
    return counter;
}

public static void main(String[] args) {
    String str = "hihi";
    int i = countHi(str);
    System.out.println("number of hi = " + i);
}

Advertisement

Answer

You compare instances (like String) with .equals (not ==). However, here you can use == with String.charAt(int). Also, I would start with the second character and compare the character at the current index with i and the previous index with h. Like,

public static int countHi(String str) {
    int counter = 0;
    for (int i = 1; i < str.length(); i++) {
        if (str.charAt(i - 1) == 'h' && str.charAt(i) == 'i') {
            counter++;
        }
    }
    return counter;
}

Alternatively, compare the character at the current index with h and the character at the next index with i (but now you need to stop iterating a character earlier). Like,

public static int countHi(String str) {
    int counter = 0;
    for (int i = 0; i < str.length() - 1; i++) {
        if (str.charAt(i) == 'h' && str.charAt(i + 1) == 'i') {
            counter++;
        }
    }
    return counter;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement