如何在C++中解析包含空格的字符串

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

本文关键字:包含 空格 字符串 C++      更新时间:2023-10-16

我有一个这样的字符串:

aaa bbb

字符串的第二部分前面有一个空格。我的目标是只解析第一部分,所以aaa。空间用完后的一切。我如何在C++中做到这一点?

std::string s = "aaa bbb";
std::string s_before_space = s.substr(0, s.find(' '));
std::string s = "aaa bbb";
s = s.substr(0, s.find_first_of(' '));
 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;
 }

或者,使用容器并使用<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

包括:

 #include <sstream>   // for ostringstream/istringstream/stringstream
 #include <algorithm> // for copy
 #include <iterator>  // for istream_iterator/back_inserter

用户关注的tokenizer,取自本网站上的一些早期帖子。

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