Finding the longest word in a string (GameMaker)

I was working on a function to get the longest word out of a string so I figured I could share it here as well!
Note: this won’t work well if your string contains the ‘@’ character as I use it to tag space characters.

 

wordCount = string_count(" ", text);
for(i=0;i<=wordCount;i++) {
    if(i==0) {
        space_pos = 0;
        next_space_pos = string_pos(" ", text);
    }
    else {
        space_pos = string_pos(" ", text);
        text = string_replace(text," ","@");
        if(i<wordCount) {
            next_space_pos = string_pos(" ", text);
        }
        else {
            next_space_pos = string_length(text)-1;
        }
    }
    if(next_space_pos-space_pos > string_length(longestWord)) {    
        longestWord = string_copy(text,space_pos+1,next_space_pos-space_pos);
    }
}
text = string_replace_all(text,"@"," ");

View all my articles...