0

How do retrieve the first word of a string in C++?

For example,

"abcde fghijk"

I would like to retrieve abcde. Also what do I do to retrieve fghijk? Is there a convenient function for this or should I just code it?

Mark
  • 8,408
  • 15
  • 57
  • 81

3 Answers3

4

Use split...

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t "));
Andrew White
  • 52,720
  • 19
  • 113
  • 137
2

Use stringstreams (<sstream> header)

std::string str ="abcde fghijk";
std::istringstream iss(str);
std::string first, second;
iss >> first >> second;
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
2
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>

std::vector<std::string> get_words(std::string sentence)
{
        std::stringstream ss(sentence);
        std::istream_iterator<std::string> begin(ss);
        std::istream_iterator<std::string> end;
        return std::vector<std::string>(begin, end);
}
int main() {
        std::string s = "abcde fghijk";
        std::vector<std::string> vstrings = get_words(s);

        //the vector vstrings contains the words, now print them!
        std::copy(vstrings.begin(), vstrings.end(), 
                  std::ostream_iterator<std::string>(std::cout, "\n"));
        return 0;
}

Output:

abcde
fghijk

Online demo : http://ideone.com/9RjKw

Nawaz
  • 353,942
  • 115
  • 666
  • 851