I am practicing over the summer to try and get better and I am a little stuck on the following:
http://www.javabat.com/prob/p123384
Given a string, return a new string where the first and last chars have been exchanged.
Examples:
frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"
Code:
public String frontBack(String str)
{
String aString = "";
if (str.length() == 0){
return "";
}
char beginning = str.charAt(0);
char end = str.charAt(str.length() - 1);
str.replace(beginning, end);
str.replace(end, beginning);
return str;
}
Rather than using the
String.replacemethod, I’d suggest using theString.substringmethod to get the characters excluding the first and last letter, then concatenating thebeginningandendcharacters.Furthermore, the
String.replacemethod will replace all occurrences of the specified character, and returns a newStringwith the said replacements. Since the return is not picked up in the code above, theString.replacecalls really don’t do much here.This is because
Stringin Java is immutable, therefore, thereplacemethod cannot make any changes to the originalString, which is thestrvariable in this case.Also to add, this approach won’t work well with
Strings that have a length of 1. Using the approach above, a call toString.substringwith the sourceStringhaving a length of 1 will cause aStringIndexOutOfBoundsException, so that will also have to be taken care of as a special case, if the above approach is taken.Frankly, the approach presented in indyK1ng’s answer, where the
char[]is obtained from theStringand performing a simple swap of the beginning and end characters, then making aStringfrom the modifiedchar[]is starting to sound much more pleasant.