我希望在字符串中切换2个随机字符。例如,如果我以“abcdef”开头,我希望计算机生成2个随机数,并切换2个字符。所以可能的结果可能是“afcdeb”。
答案 0 :(得分:0)
答案 1 :(得分:0)
您可以使用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();
答案 2 :(得分:0)
生成0和(字符串-1的长度)
之间的随机数index1和index2int 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());