Snippet. Vala. Convert String to Array

The function string_to_array converts a string into an array of strings each string containing one character in Vala.

//======================== START OF FUNCTION ==========================//
// FUNCTION: string_to_array                                           //
//=====================================================================//
string[] string_to_array(string str) {
    string[] array = new string[str.length];

    for (int i = 0; i < str.length; i++){
        array[i] = str.get_char(str.index_of_nth_char(i)).to_string();
    }
    
    return array;
}
//=====================================================================//
// FUNCTION: string_to_array                                           //
//========================= END OF FUNCTION ===========================//

Example

string hi = "Hello, world!";

string[] hi_array = string_to_array(hi);

for (int i=0; i<hi_array.length; i++){
    stdout.printf(hi_array[i] + "\n");
}

Result

H
e
l
l
o
,

w
o
r
l
d
!

Updated on: 23 Nov 2024