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,064
  • 6
  • 40
  • 55
user1056635
  • 745
  • 2
  • 9
  • 12

4 Answers4

9
std::string s = "aaa bbb";
std::string s_before_space = s.substr(0, s.find(' '));
hmjd
  • 117,013
  • 19
  • 199
  • 247
3
std::string s = "aaa bbb";

s = s.substr(0, s.find_first_of(' '));
jrok
  • 52,730
  • 9
  • 104
  • 139
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
  • 350,152
  • 45
  • 431
  • 590
-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,287
  • 29
  • 107
  • 180
  • 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