开发者

Randomize capital letters

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜