

char lastChar myString.charAt(myString.length() - 1) String. We also have to use 'return' methods, but I am confused as to how they should be used. The point of this lab is to find the first and last letter of each string. My teacher is out of town this weekend and so he can't answer my questions. Here are two ways to get the last character of a String: char. This lab we are doing in class is giving me a lot of trouble, and I wanted someone to help explain it to me. Using the approach above, a call to String.substring with the source String having a length of 1 will cause a StringIndexOutOfBoundsException, so that will also have to be taken care of as a special case, if the above approach is taken.įrankly, the approach presented in indyK1ng's answer, where the char is obtained from the String and performing a simple swap of the beginning and end characters, then making a String from the modified char is starting to sound much more pleasant. The other answers contain a lot of needless text and code. This is because String in Java is immutable, therefore, the replace method cannot make any changes to the original String, which is the str variable in this case.Īlso to add, this approach won't work well with Strings that have a length of 1. substringUTF-8 String with first character removed: String with last character removed: String with both the first and last characters removed: If the string is known to consist of 8-byte characters, we can use a simpler method.

For more details on String objects, go to the Java API.Swapping the first and the last letter of a string in Java - Stack. apple -> eppla It compiled fine and works fine with an empty string or a string with one character only.

Apple java substring first and last character code#
Since the return is not picked up in the code above, the String.replace calls really don't do much here. Strings can be split into an array of chars and can be made with an array of chars. I'm just trying to swap the first letter and the last letter of a string. charAt (string length 1) returns the last character from this string. Call charAt () method on the string and pass one less than string length as argument. Rather than using the String.replace method, I'd suggest using the String.substring method to get the characters excluding the first and last letter, then concatenating the beginning and end characters.įurthermore, the String.replace method will replace all occurrences of the specified character, and returns a new String with the said replacements. To get last character from String in Java, use String.charAt () method.
