Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java สร้างสตริงสุ่ม (Random String)


บทนำ

ในบทความนี้ เราจะเรียนรู้วิธีการสร้างสตริงสุ่ม (Random String) ใน Java สตริงเป็นชนิดข้อมูลที่ประกอบด้วยตัวอักษรหนึ่งตัวขึ้นไป และล้อมรอบด้วยเครื่องหมายคำพูดคู่ (" ")

ตัวอย่างการทำงาน

อินพุทตัวอย่าง:

The size of the string is defined as: 10

เอาต์พุทที่คาดหวัง (ตัวอย่าง):

Random string: ink1n1dodv

อัลกอริทึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศจำนวนเต็ม string_size, สตริง alpha_numeric และออบเจ็กต์ StringBuilder string_builder
ขั้นตอนที่ 3 - กำหนดค่า
ขั้นตอนที่ 4 - วนลูป 10 ครั้ง สร้างค่าสุ่มด้วย Math.random() และต่อท้ายด้วย append()
ขั้นตอนที่ 5 - แสดงผลลัพธ์
ขั้นตอนที่ 6 - จบการทำงาน

ตัวอย่างที่ 1: เขียนในฟังก์ชัน main โดยตรง

public class RandomString {
    public static void main(String[] args) {
        int string_size = 10;
        System.out.println("The size of the string is defined as: " + string_size);
        String alpha_numeric = "0123456789" + "abcdefghijklmnopqrstuvxyz";
        StringBuilder string_builder = new StringBuilder(string_size);
        for (int i = 0; i < string_size; i++) {
            int index = (int)(alpha_numeric.length() * Math.random());
            string_builder.append(alpha_numeric.charAt(index));
        }
        String result = string_builder.toString();
        System.out.println("The random string generated is: " + result);
    }
}

เอาต์พุท

The size of the string is defined as: 10
The random string generated is: ink1n1dodv

ตัวอย่างที่ 2: ใช้เมธอดแยก (Object-Oriented Style)

public class RandomString {
    static String getAlphaNumericString(int string_size) {
        String alpha_numeric = "0123456789" + "abcdefghijklmnopqrstuvxyz";
        StringBuilder string_builder = new StringBuilder(string_size);
        for (int i = 0; i < string_size; i++) {
            int index = (int)(alpha_numeric.length() * Math.random());
            string_builder.append(alpha_numeric.charAt(index));
        }
        return string_builder.toString();
    }
    
    public static void main(String[] args) {
        int string_size = 10;
        System.out.println("The size of the string is defined as: " + string_size);
        System.out.println("The random string generated is: ");
        System.out.println(RandomString.getAlphaNumericString(string_size));
    }
}

เอาต์พุท

The size of the string is defined as: 10
The random string generated is: ink1n1dodv

วิธีอื่นๆ ที่ทันสมัยกว่า (Java 8+):

// ใช้ Random.ints() + Stream API
public static String randomString(int length) {
    String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    return new Random().ints(length, 0, chars.length())
        .mapToObj(chars::charAt)
        .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
        .toString();
}

// ใช้ UUID (สำหรับ unique ID)
String random = UUID.randomUUID().toString().replace("-", "").substring(0, length);

// ใช้ SecureRandom (สำหรับความปลอดภัย/คริปโต)
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[length];
random.nextBytes(bytes);
String result = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);

หมายเหตุ: ตัวอย่างต้นฉบับขาดตัวอักษร 'w' และ 'x' ใน alpha_numeric (ควรเป็น uvwxyz)