I'm looking to switch 2 random characters in a string. For example, if I start with "abcdef", I'd like the computer to generate 2 random numbers, and switch 2 characters. So a possible outcome could be "afcdeb".
Asked
Active
Viewed 1,589 times
3 Answers
0
- get the length of the string
- get 2 different int random numbers between 0 and the length of the string: rand1 and rand2.
- I think you should convert the string to an array of chars.
- Do the swap within the array with the 2 random numbers.
- Convert the array to a string.
0
You can use the following approach using the StringBuilder.
String string="Your String";
int length=string.length();
Random rand=new Random();
int one=0;
int two=0;
/*
generate two random indexes which are not equal to each other.
*/
while(length>=2 && one==two){
one=rand.nextInt(length);
two=rand.nextInt(length);
}
//use String builder and interchange the characeters.
StringBuilder builder=new StringBuilder(string);
builder.setCharAt(one,string.charAt(two));
builder.setCharAt(two,string.charAt(one));
String newString=builder.toString();

Imesha Sudasingha
- 3,462
- 1
- 23
- 34
-
Sorry to be a pain, but is there a way to do it without StringBuilder? – Harrison Bergman Apr 15 '16 at 04:32
-
There's a way. You an concatenate substrings and create the new string. But the code will be bit complex. As in [this](http://stackoverflow.com/questions/6952363/replace-a-character-at-a-specific-index-in-a-string) question – Imesha Sudasingha Apr 15 '16 at 04:36
0
Generate random numbers index1 and index2 between 0 and (length of string -1)
int index1= randomNumber1;
int index2= randomNumber2;
String str ="abcdef";
String charSwap1= str.substring(index1, index1+1);
String charSwap2= str.substring(index2, index2+1);
StringBuilder builder=new StringBuilder();
builder.append(str);
builder.replace(index1,index1+1,charSwap2);
builder.replace(index2,index2+1,charSwap1);
System.out.println(builder.toString());

annu
- 75
- 6
-
This returns an error in String charSwap1= str.substring(index1, index1+1); String charSwap2= str.substring(index2, index2+1); The index is out of range – Harrison Bergman Apr 17 '16 at 20:50
-
startIndex is inclusive whereas the endIndex is exclusive.. It should not return any error as index+1 will be 2 in your case and index2+1 should be 6 which is within the string range. Are you getting error for charSwap2 or charSwap1 ?? If for charSwap2 use this instead. str.substring(index2) if it is the last character. – annu Apr 18 '16 at 04:48