Snippet. Vala. Generate Random String

Random strings are very useful. For instance, to generate a new password for a user. This convenient Vala function will generate a random string with optional length and optional character set. The default length is 8, and the default character set includes the Latin alphabet in upper case (A-Z) and small case (a-z), and the numbers from 0 to 9.

//======================== START OF FUNCTION ==========================//
// FUNCTION: string_random                                             //
//=====================================================================//
string string_random(int length = 8, string charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"){
    string random = "";

    for(int i=0;i<length;i++){
        int random_index = Random.int_range(0,charset.length);
        string ch = charset.get_char(charset.index_of_nth_char(random_index)).to_string();
        random += ch;
    }
	
    return random;
}
//=====================================================================//
// FUNCTION: string_random                                             //
//========================= END OF FUNCTION ===========================//

Example

// Default. Upper and smallcase numbers
string random_default = string_random();
stdout.printf(random_default + "\n");   // Prints B4KzA6IC
	
// Random string of only small case letters and 10 characters long
string random_smallcase = string_random(10,"abcdefghijklmnopqrstuvwxyz");
stdout.printf(random_smallcase + "\n"); // Prints nuwhsugjgp
	
// Random string of only numbers and 12 characters long
string random_numbers = string_random(12,"1234567890");
stdout.printf(random_numbers + "\n");   // Prints 064392356885

Updated on: 23 Nov 2024