How to swap String characters in Java?
Asked Answered
M

16

36

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

Mallemuck answered 5/6, 2009 at 14:35 Comment(1)
Please remember that you have to return a new String, because java String's are immutable.Breban
B
64

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
Bonanno answered 5/6, 2009 at 14:39 Comment(4)
Nice. Not sure why I went straight to StringBuilder instead of thinking about a char array.Irvingirwin
@Jon Skeet: My first thought was actually to build up a new String, but since the requirements were a swap, so I thought the char array would be easier. :)Bonanno
Just to add, the String class uses a char[] to keep its string data internally. This can be seen from browsing the source for the OpenJDK. So it may be old-fashioned, but arrays are used in the String class itself.Bonanno
Very nice! I like how you did this without a StringBuilder.Assiduous
M
31

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

 String second = first.replaceFirst("(.)(.)", "$2$1");
Meatus answered 5/6, 2009 at 14:38 Comment(1)
I like the look of your regular expression.Detent
E
11

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();
    }
}
Elinorelinore answered 5/6, 2009 at 20:2 Comment(0)
N
9
StringBuilder sb = new StringBuilder("abcde");
sb.setCharAt(0, 'b');
sb.setCharAt(1, 'a');
String newString = sb.toString();
Nel answered 30/3, 2014 at 14:2 Comment(0)
A
7
static String  string_swap(String str, int x, int y)
{

    if( x < 0 || x >= str.length() || y < 0 || y >= str.length())
    return "Invalid index";

    char arr[] = str.toCharArray();
    char tmp = arr[x];
    arr[x] = arr[y];
    arr[y] = tmp;

    return new String(arr);
}
Alleen answered 10/10, 2015 at 3:10 Comment(0)
M
2

String.toCharArray() will give you an array of characters representing this string.

You can change this without changing the original string (swap any characters you require), and then create a new string using String(char[]).

Note that strings are immutable, so you have to create a new string object.

Mcgovern answered 5/6, 2009 at 14:40 Comment(0)
A
1

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;
    }
}
Amity answered 24/7, 2012 at 17:15 Comment(0)
G
0

String.replaceAll() or replaceFirst()

String s = "abcde".replaceAll("ab", "ba")

Link to the JavaDocs String API

Grivet answered 5/6, 2009 at 14:37 Comment(1)
This assumed that you will know the characters to be swapped ahead of time, which doesn't seem like a usable solution in most cases.Florey
N
0

Here's a solution with a StringBuilder. It supports padding resulting strings with uneven string length with a padding character. As you've guessed this method is made for hexadecimal-nibble-swapping.

/**
 * Swaps every character at position i with the character at position i + 1 in the given
 * string.
 */
public static String swapCharacters(final String value, final boolean padding)
{
   if ( value == null )
   {
      return null;
   }

   final StringBuilder stringBuilder = new StringBuilder();
   int posA = 0;
   int posB = 1;
   final char padChar = 'F';

   // swap characters
   while ( posA < value.length() && posB < value.length() )
   {
      stringBuilder.append( value.charAt( posB ) ).append( value.charAt( posA ) );
      posA += 2;
      posB += 2;
   }

   // if resulting string is still smaller than original string we missed the last
   // character
   if ( stringBuilder.length() < value.length() )
   {
      stringBuilder.append( value.charAt( posA ) );
   }

   // add the padding character for uneven strings
   if ( padding && value.length() % 2 != 0 )
   {
      stringBuilder.append( padChar );
   }

   return stringBuilder.toString();
}
Nitid answered 15/10, 2015 at 11:32 Comment(0)
T
0
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();
}
Temblor answered 4/4, 2016 at 21:45 Comment(0)
H
0

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)));
  }
}
Herby answered 25/7, 2016 at 7:26 Comment(0)
M
0
//this is a very basic way of how to order a string alpha-wise, this does not use anything fancy and is great for school use

package string_sorter;

public class String_Sorter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String word = "jihgfedcba";
        for (int endOfString = word.length(); endOfString > 0; endOfString--) {

            int largestWord = word.charAt(0);
            int location = 0;
            for (int index = 0; index < endOfString; index++) {

                if (word.charAt(index) > largestWord) {

                    largestWord = word.charAt(index);
                    location = index;
                }
            }

            if (location < endOfString - 1) {

                String newString = word.substring(0, location) + word.charAt(endOfString - 1) + word.substring(location + 1, endOfString - 1) + word.charAt(location);
                word = newString;
            }
            System.out.println(word);
        }

        System.out.println(word);
    }

}
Miscarry answered 28/12, 2018 at 1:21 Comment(0)
S
0
s = s.substring(0, firstChar)
            +s.charAt(secondChar)
            +s.substring(firstChar + 1, secondChar)
            +s.charAt(firstChar)
            +s.substring(secondChar+1);
Showing answered 11/12, 2020 at 12:25 Comment(2)
Please add some textual explanation accompagnying your response. Only code responses may not be very clear. What are firstChar, secondChar...? Also, may be a minimal working example is a good choice of responsesMelodramatize
firstChar and secondChar represents the indexes of a string that being swapShowing
M
0
private static void interchangeSpecificCharInString(String originalStr, String inter1, String inter2) {
        List<Character> characterList = new ArrayList<>();

        for (char c : originalStr.toCharArray()) {
            characterList.add(c);
        }

        int index1 = characterList.indexOf(inter1.charAt(0));
        int index2 = characterList.indexOf(inter2.charAt(0));

        characterList.set(index1, inter2.charAt(0));
        characterList.set(index2, inter1.charAt(0));

        StringBuilder sb = new StringBuilder();
        for (char c : characterList) {
            sb.append(c);
        }

        System.out.println(sb.toString());
    }

If the string that you want to pass on is "Random" then you want to interchange "R" and "m" then here the originalStr will be Random, inter1 will be R and inter2 will be m.

Maggy answered 23/9, 2021 at 9:26 Comment(0)
A
-1
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);

    }
}
Augustineaugustinian answered 12/9, 2013 at 9:17 Comment(0)
M
-1

The following line of code will swap the first two characters in str:

return str.charAt(1) + str.charAt(0) + str.substring(2);
Moustache answered 21/8, 2016 at 13:42 Comment(3)
Please add some explanation, too, not just a line of code?Chalmers
This produces a completely wrong result. Hint: computational operators of equal precedence are left associative in Java, as in nearly all programming languages ever.Bacolod
//you can do that...Hint : that code work in case String length large than 2 >>>>>>>> >>>>>>>>>>>>>>> package to.pkgtry; import java.util.Scanner; public class ToTry { public static String swap(String str) { String ret = "" + str.charAt(1) + str.charAt(0) + str.substring(2) ; return ret ; } public static void main(String[] args) { String s = swap("abcg") ; System.out.println(s); } }Moustache

© 2022 - 2024 — McMap. All rights reserved.