java如何将随机字符行转换为字符串?

Java. How to convert random line of characters to a string?

本问题已经有最佳答案,请猛点这里访问。

我是爪哇人。我大约三天前就开始了。我想做一行随机字符并把它们放入一个字符串中。谢谢您。

1
2
3
4
5
6
7
8
9
10
11
12
    import java.util.Random;
      public class test{
      public static void main (String[]args){

final String alphabet ="abcdefghigklmnopqrstuvwxyz";
final int N = alphabet.length();
Random r = new Random();

for (int i = 0; i < 50; i++) {
    String s = alphabet.charAt(r.nextInt(N));
    // System.out.println(alphabet.charAt(r.nextInt(N)));
}}}


最简单的方法是使用StringBuilder或StringBuffer(语法相同)。

1
2
3
4
5
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 50; i++) {
    sb.append(alphabet.charAt(r.nextInt(N)));
}
String s = sb.toString();


使用StringBuilder添加字符以生成字符串-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Random;

public class test{

    public static void main (String[]args){
        final String alphabet ="abcdefghigklmnopqrstuvwxyz";
        final int N = alphabet.length();
        Random r = new Random();
        StringBuilder builder = new StringBuilder();

        // make strings with 50 characters
        for (int i = 0; i < 50; i++) {
            builder.append(alphabet.charAt(r.nextInt(N)));
        }

        System.out.println(builder.toString();
    }
}


最简单的方法是将带有加法运算符("+")的字符添加到字符串中。它的功能过载了,所以应该可以工作。

随着Java变得更加舒适,您应该开始使用StrugBuudor或StringBuffer。


使用StringBuilder

1
2
3
4
5
StringBuilder sb = new StringBuilder()
for (int i = 0; i < 50; i++) {
    sb.append(alphabet.charAt(r.nextInt(N)))
}
String s = sb.toString()

将随机字符附加到充当文本缓冲区的StringBuilder

1
2
3
4
5
6
7
StringBuilder sb = new StringBuilder();

for (int i = 0; i < 50; i++) {
    sb.append(alphabet.charAt(r.nextInt(N)));
}

System.out.println(sb);

1
2
3
4
String s ="";
for (int i = 0; i < 50; i++) {
    s += alphabet.charAt(r.nextInt(N));
}