How can I swap two characters in a String
? For example, \"abcde\"
will become \"bacde\"
.
String.replaceAll() or replaceFirst()
String s = "abcde".replaceAll("ab", "ba")
Link to the JavaDocs String API
import java.io.*;
class swaping
{
public static void main(String args[])
{
String name="premkumarg";
int len=name.length();
char[] c = name.toCharArray();
for(int i=0;i<len-1;i=i+2)
{
char temp= c[i];
c[i]=c[i+1];
c[i+1]=temp;
}
System.out.println("Swapping string is: ");
System.out.println(c);
}
}
I think this should help.
import java.util.*;
public class StringSwap{
public static void main(String ar[]){
Scanner in = new Scanner(System.in);
String s = in.next();
System.out.println(new StringBuffer(s.substring(0,2)).reverse().toString().concat(s.substring(2)));
}
}
This has been answered a few times but here's one more just for fun :-)
public class Tmp {
public static void main(String[] args) {
System.out.println(swapChars("abcde", 0, 1));
}
private static String swapChars(String str, int lIdx, int rIdx) {
StringBuilder sb = new StringBuilder(str);
char l = sb.charAt(lIdx), r = sb.charAt(rIdx);
sb.setCharAt(lIdx, r);
sb.setCharAt(rIdx, l);
return sb.toString();
}
}
Here is java sample code for swapping java chars recursively.. You can get full sample code at http://java2novice.com/java-interview-programs/string-reverse-recursive/
public String reverseString(String str){
if(str.length() == 1){
return str;
} else {
reverse += str.charAt(str.length()-1)
+reverseString(str.substring(0,str.length()-1));
return reverse;
}
}
public static String shuffle(String s) {
List<String> letters = Arrays.asList(s.split(""));
Collections.shuffle(letters);
StringBuilder t = new StringBuilder(s.length());
for (String k : letters) {
t.append(k);
}
return t.toString();
}