Skip to content

Instantly share code, notes, and snippets.

@waynebaby
Forked from anonymous/makeRandom.java
Created November 5, 2012 10:10
Show Gist options
  • Save waynebaby/4016449 to your computer and use it in GitHub Desktop.
Save waynebaby/4016449 to your computer and use it in GitHub Desktop.
String makeRandom(String content)
{
if(content == null)
throw Exception("Null input vlaue");
if(content.length <= 3)
return content;
else
return generateRadom(content);
}
String generateRandom(String content)
{
StringBuilder builder = new StringBuilder();
String[] wordList = content.split(" "); //split 浪费啊。。
for(String word: wordList)
{
builder.append(randomizeWord(word));
builder.append(' ');
}//末尾会多一个 ' '的。。。
return builder.toString();
}
String randomizeWord(String word)
{
if(word.length <= 3)
return word;
else
{
StringBuilder builder = new StringBuilder(word);
Random rnd = new Random();
for(int i = 1; i < (word.length - 1) / 2; i++)
{
int randInt = rnd.nextInt(word.length - i) + 1;
swap(builder, i, randInt);
}
}
}
void swap(StringBuilder builder, int i, int j) //这算滥用builder了吧,每次swap都会产生很多对象呢
{
Char temp = builder[i];
builder[i] = builder[j];
builder[j] = temp;
}
@dantewang
Copy link

StringBuilder可以数组方式使用??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment