views:

201

answers:

3

Guys,

I need to be able to (in C language) loop over a few lines of text where each line has some text in it where words are delimited by a variable number of white spaces. How can I detect the spaces and split each line into some kind of array so that I can put each word in a separate word tag in each line?

Any advice would be much appreciated. Thanks

A: 

One way:

char* cp = strtok(inputString, " \t\n");
while (cp) {
    // cp points to word in inputString, do something with it
    cp = strtok(0, " \t\n");  // get next word
}

If you can't modify inputString -- as strtok() does -- you can loop over the string, testing each character with isspace(), from ctype.h.

Warren Young
A: 

You can use strtok() function to split into tokens. See strtok. It shows how to use strtok and split lines into words by space delimited.

rjoshi
A: 

You could do this:

start = end = 0;

while (str[end]) {
    // extract word
    while(str[end] && !isspace(str[end])) {
        end++;
    }
    // word found between str[start] and str[end]
    // do something with it

    // skip whitespaces
    while (str[end] && isspace(str[end])) {
        end++;
    }
    start = end;
}
Ashwin