Android 随机字符串生成器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/12116092/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android random string generator
提问by Defus
I have a problem.
I want to draw a random String something like this aXcFg3s2.
What i doing bad ?
How change my random()
我有个问题。我想绘制一个像 aXcFg3s2 这样的随机字符串。我在做什么不好?如何改变我的random()
private String random;
private String charsEntered;
private EditText et;
private Button ok;
CaptchaInterface.OnCorrectListener mCorrectListener;
public void setOnCorrectListener(CaptchaInterface.OnCorrectListener listener) {
    mCorrectListener = listener;
}
public TextCaptcha(Context context) {
    super(context);
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
public static String random() {
    Random generator = new Random();
    String x = (String) (generator.nextInt(96) + 32);
    return x;
}
public void onCreate(Bundle icicle) {
    setContentView(R.layout.main);
    random = random();
    TextView display = (TextView) findViewById(R.id.textView1);
    display.setText("Random Number: " + random); // Show the random number
    et = (EditText) findViewById(R.id.etNumbers);
    ok = (Button) findViewById(R.id.button1);
    ok.setOnClickListener(this);
}
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    try {
        charsEntered = et.getText().toString();
    } catch (NumberFormatException nfe) {
        Toast.makeText(et.getContext(), "Bla bla bla",
                Toast.LENGTH_LONG).show();
    }
    if (random == charsEntered) {
        Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
    }
}
回答by android developer
the problem is that you've handled only a single character instead of using a loop.
问题是您只处理了一个字符而不是使用循环。
you can create an array of characters which has all of the characters that you wish to allow to be in the random string , then in a loop take a random position from the array and add append it to a stringBuilder . in the end , convert the stringBuilder to a string.
您可以创建一个字符数组,其中包含您希望允许在随机字符串中的所有字符,然后在循环中从数组中获取随机位置并将其添加到 stringBuilder 中。最后,将 stringBuilder 转换为字符串。
EDIT: here's the simple algorithm i've suggested:
编辑:这是我建议的简单算法:
private static final String ALLOWED_CHARACTERS ="0123456789qwertyuiopasdfghjklzxcvbnm";
private static String getRandomString(final int sizeOfRandomString)
  {
  final Random random=new Random();
  final StringBuilder sb=new StringBuilder(sizeOfRandomString);
  for(int i=0;i<sizeOfRandomString;++i)
    sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
  return sb.toString();
  }
and on Kotlin:
在 Kotlin 上:
companion object {
    private val ALLOWED_CHARACTERS = "0123456789qwertyuiopasdfghjklzxcvbnm"
}
private fun getRandomString(sizeOfRandomString: Int): String {
    val random = Random()
    val sb = StringBuilder(sizeOfRandomString)
    for (i in 0 until sizeOfRandomString)
        sb.append(ALLOWED_CHARACTERS[random.nextInt(ALLOWED_CHARACTERS.length)])
    return sb.toString()
}
回答by bennettaur
There are a few things wrong with your code.
您的代码有一些问题。
You cannot cast from an int to a string. Cast it to a char instead. This however will only give you a single char so instead you could generate a random number for the length of your string. Then run a for loop to generate random chars. You can define a StringBuilder as well and add the chars to that, then get your random string using the toString()method
您不能从 int 转换为字符串。改为将其转换为字符。但是,这只会给您一个字符,因此您可以为字符串的长度生成一个随机数。然后运行 for 循环以生成随机字符。您也可以定义一个 StringBuilder 并将字符添加到其中,然后使用该toString()方法获取随机字符串
example:
例子:
public static String random() {
    Random generator = new Random();
    StringBuilder randomStringBuilder = new StringBuilder();
    int randomLength = generator.nextInt(MAX_LENGTH);
    char tempChar;
    for (int i = 0; i < randomLength; i++){
        tempChar = (char) (generator.nextInt(96) + 32);
        randomStringBuilder.append(tempChar);
    }
    return randomStringBuilder.toString();
}
Also, you should use random.compareTo()rather than ==
此外,您应该使用random.compareTo()而不是 ==
回答by ??-Bham
You need to import UUID. Here is the code
您需要导入 UUID。这是代码
import java.util.UUID;
id = UUID.randomUUID().toString();
回答by Defus
this is how i generate my random strings with desired characters and desired length
这就是我生成具有所需字符和所需长度的随机字符串的方式
          char[] chars1 = "ABCDEF012GHIJKL345MNOPQR678STUVWXYZ9".toCharArray();
                                StringBuilder sb1 = new StringBuilder();
                                Random random1 = new Random();
                                for (int i = 0; i < 6; i++)
                                {
                                    char c1 = chars1[random1.nextInt(chars1.length)];
                                    sb1.append(c1);
                                }
                                String random_string = sb1.toString();  
回答by Android Dev
You can simply use the following method to generate random String with 5 character and it will return arrayList of random String
您可以简单地使用以下方法生成具有 5 个字符的随机字符串,它将返回随机字符串的 arrayList
public ArrayList<String> generateRandomString() {
    ArrayList<String> list = new ArrayList<>();
    Random rnd = new Random();
    String str = "";
    String randomLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    String randomLetterSmall = "abcdefghijklmnopqrstuvwxyz";
    for (int n = 0; n < 50; n++) {
        str = String.valueOf(randomLetters.charAt(rnd.nextInt(randomLetters.length())));
        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
        //Copy above line to increase character of the String
        list.add(str);
    }
    Collections.sort(list);
    return list;
}
回答by Aryan Moradi
This function run in kotlin ->
此函数在 kotlin 中运行 ->
fun randomString(stringLength: Int): String {
    val list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray()
    var randomS = ""
    for (i in 1..stringLength) {
        randomS += list[getRandomNumber(0, list.size - 1)]
    }
    return randomS
}
fun getRandomNumber(min: Int, max: Int): Int {
   return Random().nextInt((max - min) + 1) + min
}
Or you can use my library https://github.com/Aryan-mor/Utils-Library
或者你可以使用我的图书馆 https://github.com/Aryan-mor/Utils-Library
回答by BitByteDog
Quick one liner using the org.apache.commons.lang3.RandomStringUtilspackage.
使用org.apache.commons.lang3.RandomStringUtils包装快速的一个衬垫。
String randonString = RandomStringUtils.randomAlphanumeric(16);
Requires the library dependency in the gradle build file:
需要 gradle 构建文件中的库依赖项:
implementation 'org.apache.commons:commons-text:1.6'
回答by ORY
final  String[] Textlist = { "Text1", "Text2", "Text3"};
TextView yourTextView = (TextView)findViewById(R.id.yourTextView);
Random random = new Random();
Random random = new Random();
String randomText = TextList[random.nextInt(TextList.length)];
String randomText = TextList[random.nextInt(TextList.length)];
yourTextView.setText(randomText);
回答by LuxuryMode
You cannot cast an int to a String. Try:
您不能将 int 转换为 String。尝试:
 Random generator = new Random();
 String x = String.valueOf (generator.nextInt(96) + 32);

