user1056635
user1056635

Reputation: 795

How to parse a string containing spaces in C++?

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++?

Upvotes: 3

Views: 3387

Answers (4)

sehe
sehe

Reputation: 392863

 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

Upvotes: 3

jrok
jrok

Reputation: 55395

std::string s = "aaa bbb";

s = s.substr(0, s.find_first_of(' '));

Upvotes: 3

Avinash
Avinash

Reputation: 13257

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);
    }
}

Upvotes: -1

hmjd
hmjd

Reputation: 121961

std::string s = "aaa bbb";
std::string s_before_space = s.substr(0, s.find(' '));

Upvotes: 9

Related Questions