5

Possible Duplicate:
How do I tokenize a string in C++?

pseudocode:

    Attributes[] = Split line(' ')

How?

I have been doing this:

  char *pch;
  pch = strtok(line," ");
  while(pch!=NULL)
  {
      fputs ( pch, stdout ); 


  }

and getting a non-written, stuck, exit file. It's something wrong with this? Well, the thing isn't even meeting my pseudocode requirement, but I'm confused about how to index tokens (as char arrays) to my array, I guess I should write a 2-dim array?

2
  • 3
    The solution is different depending on whether you're using C or C++.
    – dreamlax
    Commented Nov 12, 2010 at 23:47
  • 17
    How about some of the examples from the following: codeproject.com/KB/recipes/Tokenizer.aspx They are very efficient and somewhat elegant. The String Toolkit Library makes complex string processing in C++ simple and easy.
    – Matthieu N.
    Commented Dec 8, 2010 at 5:28

3 Answers 3

8

Use strtok with " " as your delimiter.

1
  • That's great for C, for C++ see related question in my answer. Commented Nov 12, 2010 at 23:46
5

This is not quite a dup - for C++ see and upvote the accepted answer here by @Zunino.

Basic code below but to see the full glorious elegance of the answer you are going to have to click on it.

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

int main() {
    using namespace std;
    string sentence = "Something in the way she moves...";
    istringstream iss(sentence);
    copy(istream_iterator<string>(iss),
             istream_iterator<string>(),
             ostream_iterator<string>(cout, "\n"));
}

This hinges on the fact that by default, istream_iterator treats whitespace as its separator. The resulting tokens are written to cout on separate lines (per separator specified in constructor overload for ostream_iterator).

0
1

The easiest method is boost::split:

std::vector<std::string> words;
boost::split(words, your_string, boost::is_space());

Not the answer you're looking for? Browse other questions tagged or ask your own question.