ID:1603933
 
Parse (string, separator)
Zecronious edit of Ter13's Tokenize

Description

This takes any text you give it, such as the input from a user and breaks it into it's component words so that you can look at each word in the text individually.

The character or characters that separate each word is manually set so that you don't just have to use a typical space. You could use any symbol you like.

Example

var/list/words = parse("pickup 20 feathers", " ")

words:
words[1] = "pickup"
words[2] = "20"
words[3] = "feathers"


Unusual Input Example

var/list/words = parse("     pickup  20 feathers       ")

words:
words[1] = "pickup"
words[2] = "20"
words[3] = "feathers"


The code you need

#define element .
proc
parse(string, separator)
var
length = length(string)
list/words = list()
position = 1

element = findtext(string, separator, position)

while(position <= length)

if(element > position || element == 0)
words += copytext(string, position, element)

if(element)
position = element + 1
element = findtext(string, separator, position)

else position = length + 1

return words


Digressions

Questions/Problems/Requests? Comment below.

So why a parser? I enjoy text based games and the start for any text based game is a parser. With good parsing code being at a premium I thought I'd put this here in the hopes of making it easier for people to build a text based game.

Can this be used for anything other than a text based game you ask (assuming you're still reading)?
- Yes! You're only limited by what you can come up with and I'm actually quite interested to see what other ideas people can come up with.
Should be called a tokenizer. The term "parsing" with a computer science context is much broader than what your function here does, so it's a bit of a misnomer for your function. Also, deadron's texthandling library already has a function for exactly this and much more.