'Switch the first and last letters of a string
I am making a program that will switch the first and last letters of a string, but when I run it, it just replaces the last letter with the first and that's it.
public static String swap(String String3) {
//finds first & last letter of string
String firstLetter = String3.substring(0, 1);
String lastLetter = String3.substring(String3.length() - 1);
String a = String3.replace(firstLetter, lastLetter);
String z = a.replace(lastLetter, firstLetter );
return z;
public static void main(String[] args){
System.out.print("Enter your swap string: ");
Scanner scan = new Scanner(System.in);
String String3 = scan.nextLine();
System.out.println(swap(String3));
}
Can anyone tell me what i'm doing wrong?
Solution 1:[1]
String.replace
replaces all occurences of the first character by the second. That's not what you want. As an example let's assume the text abc
. The first replace will lead to cbc
and the second will lead to aba
which is what you've seen. An input string abab
will result to aaaa
as result.
You need to create a new String
to get the swap you want:
char first = text.charAt(0);
char last = text.charAt(text.length() - 1);
return last + text.substring(1, text.length() - 2) + last;
Alternatively you can use Regular Expressions:
text.replaceAll("^(.)(.*)(.)$", "$3$2$1");
I skipped the test if the length of the input text is long enough, so an input text a
will lead to an error with the first solution. The second solution would still work, because the regex doesn't match and no replacement will take place.
Solution 2:[2]
You replace the first letter with the last in a, so when you look for that letter in z there are no instances to replace. It also would replace any instance of the last letter in a.
One method would be to substring String3 & prepend/append the needed character.
public static String swap(String String3) {
//finds first & last letter of string
String firstLetter = String3.substring(0, 1);
String lastLetter = String3.substring(String3.length() - 1);
String3 = firstLetter + String3.substring(1);
String3 = String3.substring(0, String3.length() - 1) + lastLetter;
return String3;
}
public static void main(String[] args){
System.out.print("Enter your swap string: ");
Scanner scan = new Scanner(System.in);
String String3 = scan.nextLine();
System.out.println(swap(String3));
}
Solution 3:[3]
You replaced the First letter with the last, so now the First and the last are equal. Then you replaced the last with the First, which is equal to the last, so the First and the last are equal.
Solution 4:[4]
String3 = String3.substring(String3.length() - 1) + // last
String3.substring(1,String3.length() - 2) + // middle
String3.substring(0, 1); // first
Solution 5:[5]
e.g. Using "abc" as input, If you debug your code you will find out the mistake - the string before last replace is "cbc" and you are replacing "c" with "a"....hence the result
String firstLetter = String3.substring(0, 1);//a
String lastLetter = String3.substring(String3.length() - 1);//c
String a = String3.replace(firstLetter, lastLetter);//cbc
String z = a.replace(lastLetter, firstLetter);//aba
Solution 6:[6]
After the first replace you have string with lastLetter
at the first and the last position.
String a = String3.replace(firstLetter, lastLetter); // LASTxxxxLAST
After the second replace you obviosly has firstLetter
here
String z = a.replace(lastLetter, firstLetter ); // FIRSTxxxxFIRST
To avoid this try to swap first and second replace and use replaceAll
with $
sign and replaceFirst
for the second replacement
...
String z = String3.replaceAll(lastLetter + "$", firstLetter);
String a = z.replaceFirst(firstLetter, lastLetter);
return a;
Solution 7:[7]
There is also quite concise solution(but not such fast) with stream api. Convert input string to list of character, then use Collections.swap method and back to string again:
List<Character> list = String3.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
Collections.swap(list, 0, list.size() - 1);
String result = list.stream().map(Object::toString).reduce((s1, s2) -> s1 + s2).orElse("");
Solution 8:[8]
The problem in your solution are these 2 lines:
String a = str.replace(firstLetter, lastLetter); // 1
String z = a.replace(lastLetter, firstLetter); // 2
String.replace(char oldChar, char newChar)
returns a new string resulting from replacing all occurrences of oldChar
in this string with newChar
. So, when you create String a
you replace all chars equal to firstLetter
by char equal to lastLetter
.
Let's analyze with string "abbbabbb" as an input:
- after executing line 1, you'll will get "bbbbbbbb" - all
a
got replaced byb
- after executing line 2 there will be no effect, because you're trying to replace letter by itself (in the example input
b
byb
- hence no effect).
One working solution would be the following:
import java.util.Scanner;
class Answer {
public static void main(String[] args){
System.out.print("Enter your swap string: ");
try (Scanner scan = new Scanner(System.in)) {
String str = scan.nextLine();
String swapped = new String(swap(str, 0, str.length() - 1));
System.out.println(swapped);
}
}
private static char[] swap(String str, int i, int j) {
char[] chars = str.toCharArray();
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
return chars;
}
}
The benefit of this approach - it can be used to swap any 2 letters in the String
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Fireye |
Solution 2 | ItsPete |
Solution 3 | |
Solution 4 | chris01 |
Solution 5 | |
Solution 6 | |
Solution 7 | Ruslan |
Solution 8 |