繁体   English   中英

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

[英]How to parse a string containing spaces in C++?

我有一个像这样的字符串:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM