How can I swap two characters in a String
? For example, \"abcde\"
will become \"bacde\"
.
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.
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);
}