如何打乱字符串中的字符(例如 hello 可以是 ehlol 或 lleoh 或...)。我不想使用Collections.shuffle(...)
方法,有没有更简单的方法?
最佳答案
我不知道更简单的事情。但是您可以使用 Math.rand() 功能在字符长度范围内生成一个随机数而无需替换,这将为您提供随机输出
public class Shuffle {
public static void main(String[] args) {
Shuffle s = new Shuffle();
s.shuffle("hello");
}
public void shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
System.out.println(output.toString());
}
}
/*
Sample outputs
hlleo
llheo
leohl
lleho
*/
关于java - 如何在不使用 Collections.shuffle(...) 的情况下打乱字符串中的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3316674/