Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap String characters in Java?

Tags:

java

string

swap

How can I swap two characters in a String? For example, "abcde" will become "bacde".

like image 651
user107023 Avatar asked Jun 05 '09 14:06

user107023


People also ask

How do I swap two characters in a string?

As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.


2 Answers

Since String objects are immutable, going to a char[] via toCharArray, swapping the characters, then making a new String from char[] via the String(char[]) constructor would work.

The following example swaps the first and second characters:

String originalString = "abcde";  char[] c = originalString.toCharArray();  // Replace with a "swap" function, if desired: char temp = c[0]; c[0] = c[1]; c[1] = temp;  String swappedString = new String(c);  System.out.println(originalString); System.out.println(swappedString); 

Result:

abcde bacde 
like image 89
coobird Avatar answered Sep 28 '22 07:09

coobird


'In' a string, you cant. Strings are immutable. You can easily create a second string with:

 String second = first.replaceFirst("(.)(.)", "$2$1"); 
like image 40
toolkit Avatar answered Sep 28 '22 07:09

toolkit