0

Possible Duplicate:
Splitting a string in C++

How do I read a bunch of words separated by spaces into an array?

Say I have this sentence:

"I like frogs"

And this array:

string mySentenceArray[2]

I would like to make

mySentenceArray[0] = I
mySentenceArray[1] = like
mySentenceArray[2] = frogs

Just as an example. (Please no one tell me to hard code the sentence I just wrote, it's an example.)

Community
  • 1
  • 1
David
  • 95
  • 8

4 Answers4

0

You can turn a string into a series of tokens and put those tokens into an array. Consider this: http://www.cplusplus.com/reference/clibrary/cstring/strtok/

Conqueror
  • 4,265
  • 7
  • 35
  • 41
  • 1
    `strtok` is awkward to use on a `std::string`, since it requires a mutable character array, and there's no way to access that directly from the `string`. It's also not thread-safe. – Mike Seymour Oct 03 '12 at 03:44
0

There are several ways:

  1. Use strtok. But it's C-function, not C++. Mixing C and C++ is bad style. Moreover strtok function isn't threadsafe.

  2. Use any of std::string::find method. It's complicated.

  3. Use std::stringstream class. It needs too much steps.

  4. Use boost::algorithm::string::split. I prefer this way. It's simple and fast.

fasked
  • 3,555
  • 1
  • 19
  • 36
0

Unless I had some other uses to justify adding an extra library, I'd probably just using a stringstream:

std::istringstream buffer("I like frogs");

std::vector<std::string> words((std::istream_iterator<std::string>(buffer)), 
                                std::istream_iterator<std::string>());

std::copy(words.begin(), words.end(), 
          std::ostream_iterator<std::string>(std::cout, "\n"));
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

Using just the standard library:

istringstream sentence("I like frogs");
vector<string> words(
    (istream_iterator<string>(sentence)), 
    (istream_iterator<string>()));

Note that unnecessary-seeming parentheses are actually necessary on at least one of the constructor arguments, otherwise you will be vexed by the most vexing parse.

Alternatively, Boost provides some useful string algorithms, including split:

string sentence("I like frogs");
vector<string> words;
boost::algorithm::split(words, sentence, boost::algorithm::is_space());
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644