3

I have a string like this:

aaa bbb

There is a space before the 2nd part of the string. My goal is to parse only the first part, so aaa. Everything after the space is out. How can I do this in C++?

razlebe
  • 7,134
  • 6
  • 42
  • 57
user1056635
  • 785
  • 2
  • 9
  • 12

4 Answers4

9
std::string s = "aaa bbb";
std::string s_before_space = s.substr(0, s.find(' '));
hmjd
  • 120,187
  • 20
  • 207
  • 252
3
std::string s = "aaa bbb";

s = s.substr(0, s.find_first_of(' '));
jrok
  • 54,456
  • 9
  • 109
  • 141
3
 std::string s = "aaa bbb";
 std::istringstream ss(s);

 std::string token;
 if (ss>>token)   // or: while(ss>>token) for _all_ tokens
 { 
      std::cout << "first token only: " << token << std::endl;
 }

Alternatively, with a container and using <algorithm>

 std::string s = "aaa bbb";
 std::istringstream ss(s);

 std::vector<std::string> elements;
 std::copy(std::istream_iterator<std::string>(ss),
           std::istream_iterator<std::string>(),
           std::back_inserter(elements));

 // elements now contains the whitespace delimited tokens

Includes:

 #include <sstream>   // for ostringstream/istringstream/stringstream
 #include <algorithm> // for copy
 #include <iterator>  // for istream_iterator/back_inserter
sehe
  • 374,641
  • 47
  • 450
  • 633
-1

user following tokenizer, taken from some earlier post on this site.

void Tokenize(const std::string& str, std::vector<std::string>& tokens,const std::string& delimiters = " ") {
    std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    std::string::size_type pos     = str.find_first_of(delimiters, lastPos);
    while (std::string::npos != pos || std::string::npos != lastPos){
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        lastPos = str.find_first_not_of(delimiters, pos);
        pos = str.find_first_of(delimiters, lastPos);
    }
}
Avinash
  • 12,851
  • 32
  • 116
  • 186
  • 1
    But he only wants the first part, not all. General tokenization here = waste of performance. -1 because you just pasted without explanation. – Sebastian Mach Nov 24 '11 at 11:22