Search code examples
stringsplitgame-maker

How to split a string into multiple strings if spaces are detected (GM:Studio)


I made a console program, but the problem is that it doesn't allow parameters to be inserted. So I'm wondering how would I split a single string into multiple strings to achieve what I need. E.g.: text="msg Hello" would be split into textA="msg" and textB="Hello"

This is the main console code so far (just to show the idea):

if (keyboard_check_pressed(vk_enter)) {
    text_console_c = asset_get_index("scr_local_"+string(keyboard_string));
    if (text_console_c > -1) {
        text_console+= "> "+keyboard_string+"#";
        script_execute(text_console_c);
        text_console_c = -1;
    }
    else if (keyboard_string = "") {
        text_console+= ">#";
    }
    else {
        text_console+= "> Unknown command: "+keyboard_string+"#";
    };

    keyboard_string = "";
}

Solution

  • Something like this may help, haven't tested it out but if you can follow what is going on its a good place to start.

    Text = "msg Hello"
    counter = 0
    stringIndex = 0
    for (i = 0; i < string_length(text); i++)
    {
        if string_char_at(text,i) == " "
        {
            counter++
            stringIndex = 0
        } else {
            string_insert(string_char_at(text,i),allStrings(counter),stringIndex)
            stringIndex++
        }
    }
    

    allStrings should be an array containing each of the separate strings. Whenever a " " is seen the next index of allStrings starts having it's characters filled in. stringIndex is used to add the progressive characters.