Explode String by Delimiter


GM Version: 1.4 & 2
Target Platform: ALL
Download: N/A
Links: N/A

Typically you can explode a string by a delimiter. A good example might be C# or PHP. You can say, explode this string by a comma and place the pieces into an array. I couldn't find a good example in GML, so I wrote one.


// Iterate through a string, explode by commas.
text = argument0;
char_string = 0;
if string_pos(",", text) != 0
    var cc = string_count(",",text);
    for (i = 0; i <= cc; i += 1) {
        if (i < cc) {
            char_string[i] = string_copy(text, 0, string_pos(",", text)-1 ); // get the piece exploded off
            text = string_copy(text, string_pos(",", text)+1, string_length(text) ); // re-write text var to be what remains
            char_string[i] = text;
    return char_string;
    return text

Let's Clone

I didn't know what you meant by 'explode' at first, but reading your code cleared that up for me haha. This is neat, and I can see it being quite useful.

This isn't important, but why did you choose to run if (i < cc) in a loop where you can control that i is always less than cc? You could simply run what's in your else condition after the loop passes, unless I'm overlooking something.

Either way, good work!