开发者

Randomize capital letters

开发者 https://www.devze.com 2023-02-11 12:04 出处:网络
Is there a simple way to, given a word String, randomise capital letters? Example: F开发者_如何学JAVAor word super I would get SuPEr or SUpER.

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

Example:

F开发者_如何学JAVAor word super I would get SuPEr or SUpER.

I am looking for a Java solution for this.


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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消