Number of times the last character appears in JAVA only use String

Viewed 65

I'm doing a part of a program, where I should see the number of times the last character appears in JAVA.

The problem is that I am new with the use of Strings ( and only can use String ). Informing a bit I have seen that with equals I can compare Strings. And with substring I can select each of the letters one by one in a loop. The problem comes when I compile, that I go out of the index of the String. And I do not understand why, since I only get to .length - 1

    String aux;
    int cont = 0;

    aux = cadena.substring(cadena.length()-1);

    for (int i = 0; i < cadena.length()-1; i++) {
        if(cadena.substring(i,1).equals(aux)) {
            cont++;
        }
    }

java.lang.StringIndexOutOfBoundsException: String index out of range:-1

In this line

if(cadena.substring(i,1).equals(aux))

2 Answers

what you have done is like "Hello".substring(3, 1)

substring method takes two arguments startIndex and endIndex. so end index should always be greater than start index.

In cadena.substring(i,1), the value of i will go from 0 to cadena.length()-2, because of condition i<cadena.length()-1

You can do something like this:

int count = 0;

char lastChar = cadena.charAt(cadena.length()-1);

for (int i = 0; i < cadena.length()-1; i++) {
   if(lastChar==cadena.charAt(i)) count++;
}
Related