Cannot invoke charAt(int) on the array type String[]

Tags: , , ,



I’m doing a function that counts digits in a string:

int countOccurences(String str) {

    // split the string by spaces in a
    String a[] = str.split(" ");

    // search for pattern in a
    int count = 0;

    for (int i = 0; i < a.length; i++) 
    {
        char b = a.charAt(i);
        if (Character.isDigit(b))
            count++;
    }

    return count;
}

The error is:

Cannot invoke charAt(int) on the array type String[]"

Any ideas how to fix that?

Answer

You are trying to invoke the charAt() method on a String[]. String[] does not have such a method, but String does. What I believe you wanted to do is:

char b = a[i].charAt(i);

This will get the char at position i in the String at position i from your String array



Source: stackoverflow