I have some random string with unknown content, what is known is that the content is alphanumeric and in lower case.
I am looking for a simple method to upper case a random number of the alpha characters in that string. The higher the randomness the better.
I can think of a few ways to do this, but none of them seem very optimal.
alright first solution:
public String randomizeCase(String myString){
Random rand = new Random();
StringBuilder build = new StringBuilder();
for(char c: myString.toCharArray()){
String s = new String(c);
if(Character.isLetter(c) && rand.nextBoolean()){
s = s.toUpperCase();
}
build.append(s);
}
return build.toString();
}
I dont like this solution because:
- 50% chance that every char is uppercased does not equal 50% chance that 50% of the chars are uppercased
- There is a chance that nothing is upped cased
- char to string conversion is ugly
Here is the code snippet for random sample problem (thanks Eyal for naming it). Not sure if that is what you are looking for.
Be aware, that this solution would run into an infinete loop if not enough lowercase letters are in the string. So you would need to tackle that as well, but I guess it is a starting point. 😉
Edit:
Here is an improved version. It does change exactly n lowercase letters into uppercase letters (if there are enough, otherwise it changes all of them). The programm does not run into infinite loops, but still running time is a problem though.