以下是隨機樣本問題(感謝Eyal命名它)的代碼片段。不知道這是你在找什麼。
請注意,如果字符串中沒有足夠的小寫字母,則此解決方案將運行到infinete循環。所以你也需要解決這個問題,但我想這是一個起點。 ;-)
String myString = "9aie3ra3nr23rr5r21t";
System.out.println(upperCaseRandom(myString, 10));
public static String upperCaseRandom(String input, int n) {
StringBuilder output = new StringBuilder(input);
Random r = new Random();
for (int i = 0; i < n; i++) {
// Pick a place
int position = r.nextInt(input.length());
// Check if lowercase alpha
if (Character.isLowerCase(output.charAt(position))) {
output.setCharAt(position, Character.toUpperCase(output.charAt(position)));
} else {
i--;
}
}
return output.toString();
}
編輯: 這裏是一個改進版本。它確切地將n個小寫字母變成大寫字母(如果有足夠的,否則它會改變所有這些字母)。該程序不會陷入無限循環,但仍然運行時間是一個問題。
public static String upperCaseRandom(String input, int n) {
final int length = input.length();
final StringBuilder output = new StringBuilder(input);
final boolean[] alreadyChecked = new boolean[length];
final Random r = new Random();
for (int i = 0, checks = 0; i < n && checks < length; i++) {
// Pick a place
int position = r.nextInt(length);
// Check if lowercase alpha
if (!alreadyChecked[position]) {
if (Character.isLowerCase(output.charAt(position))) {
output.setCharAt(position, Character.toUpperCase(output.charAt(position)));
} else {
i--;
}
checks++;
alreadyChecked[position] = true;
} else {
i--;
}
}
return output.toString();
}
也許你能簡要介紹一下你已經想出了自己的想法,然後大家一起討論那些/給予提示? – 2010-07-20 18:12:07
當你說「隨機性越高越好。」你是在尋找接近真正的隨機性的字母大寫和/或哪些字母大寫? – jball 2010-07-20 18:14:39
添加了一些蹩腳的代碼 – mkoryak 2010-07-20 18:28:53