Kimmm Kimmm - 9 days ago 7
Java Question

Swapping the first and the last letter of a string in Java?

int length = s.length();

if (length <= 1){
return s;
}

else {

return s.charAt(length) + s.substring(1, length-1) + s.charAt(0);

}


I'm just trying to swap the first letter and the last letter of a string.

eg. apple -> eppla

It compiled fine and works fine with an empty string or a string with one character only.
But with strings with several characters, it says:

StringIndexOutOfBoundsException occured - see console for stack trace


Does tht mean there's something wrong with my code???

Answer

Try this:

int length = s.length();

if (length <= 1) {
    return s;
} else {
    return s.charAt(length - 1) + s.substring(1, length - 1) + s.charAt(0);
}

The difference is s.charAt(length - 1). Remember, the string is zero-indexed, so the last character is s.charAt(length - 1).

Comments