Tiago Veloso
Tiago Veloso

Reputation: 8563

Randomize capital letters

Is there a simple way to, given a word String, randomise capital letters?

Example:

For word super I would get SuPEr or SUpER.

I am looking for a Java solution for this.

Upvotes: 2

Views: 2639

Answers (2)

aioobe
aioobe

Reputation: 421110

Here is one suggestion:

public static String randomizeCase(String str) {

    Random rnd = new Random();
    StringBuilder sb = new StringBuilder(str.length());

    for (char c : str.toCharArray())
        sb.append(rnd.nextBoolean()
                      ? Character.toLowerCase(c)
                      : Character.toUpperCase(c));

    return sb.toString();
}

Example

input: hello world
output: heLlO woRlD

(ideone.com demo)

Upvotes: 9

VoronoiPotato
VoronoiPotato

Reputation: 3183

Treat the string as an array. So now instead of

string test = "Super";

visualize it as

char test = {'S', 'u' , 'p' , 'e', 'r'}; 

Now you can iterate through the array, and apply the string.toUpperCase() across it.

Upvotes: 1

Related Questions