Basic C++ Question

Discussion in 'OT Technology' started by fishbulb, Feb 20, 2003.

  1. fishbulb

    fishbulb Active Member

    Joined:
    Oct 29, 2001
    Messages:
    6,848
    Likes Received:
    4
    Location:
    md
    Hi, is there a simple way to take a string that is several words and extra each word in it seperately to another string ? Thanks
     
  2. Scoob_13

    Scoob_13 Anything is possible, but the odds are astronomica

    Joined:
    Oct 5, 2001
    Messages:
    73,792
    Likes Received:
    38
    Location:
    Fort Worth. Hooray cowgirls.
    Well, if you know that each word is seperated by only a space, you could either run through the string, find the point in it that it's a space, then copy the string from the last space to that space (meaning that if it's starts at [0] and finds a space at [3], you copy from [0] to [3]), or you can use strtok to tokenize the string, I believe that when you use strtok you have to do something like:

    test = strtok(*string, tokencharacter);

    if that makes sense.

    There's a lot of ways that you can work with strings :)
     
  3. skinjob

    skinjob Active Member

    Joined:
    Jan 6, 2001
    Messages:
    2,337
    Likes Received:
    0
    Location:
    Aztlán
    If by string you mean character array, then you can use strtok(). The thing to remember about strtok is that it will modify your string (it'll insert NULL characters), so make a copy if you want to preserve your original string. Also, you do not need to pass in a pointer to the original string on subsequent calls, if you're still tokenizing the same string.

    Code:
    // strtok is used to find words separated by a space or tab
    // pass the string pointer to the initial call to strtok.
    // strtok will return a pointer to the first word.  It will insert
    // a NULL character where it finds a space or tab so that word
    // points to a NULL-terminated string
    word = strtok(sentence,  " \t");
    while (word)
    {
        // copy the word to another character array here
        // then call strtok again to get the next word
        word = strtok(NULL, " \t");
    }
    
    If you're using STL strings, find_first_of works somewhat similarly to strtok. It doesn't insert NULLs into your string, so you have to keep track of the indicies. You then use substr to extract the substring.

    Code:
    int next;
    int last = 0;
    // find the first occurence of whitespace
    next = sentence.find_first_of(" \t", last);
    while (next != npos)
    {
         // extract the substring
         word = sentence.substr(last, next-last);
         // then get the index of the next whitespace occurence
         last = next;
         next = sentence.find_first_of(" \t", last);
    }
    
     

Share This Page