拆分子串

时间:2010-09-17 21:45:53

标签: c++

如何以简单的方式基于另一个子字符串拆分字符串?

e.g。拆分为“\ r \ n”

message1\r\nmessage2 

=>

message1
message2

从我能够发现的内容中,boost :: tokenizer和boost :: split仅对单个字符进行操作。

编辑:

我知道我可以通过使用std :: string :: find和std :: string :: substr并且有一个循环等来实现这一点......但这不是我所说的“简单”。

4 个答案:

答案 0 :(得分:16)

尽管boost :: split确实采用了对字符进行操作的谓词,但是有一个可以在子字符串上拆分的提升string algorithm

#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <boost/algorithm/string/iter_find.hpp>
#include <boost/algorithm/string/finder.hpp>
int main()
{
    std::string input = "message1foomessage2foomessage3";

    std::vector<std::string> v;
    iter_split(v, input, boost::algorithm::first_finder("foo"));

    copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, " "));
    std::cout << '\n';
}

答案 1 :(得分:1)

您可以搜索用作拆分令牌的子字符串的下一个出现位置。这样的方法可能会返回下一次出现的索引,并且你可以自己拆分字符串。

答案 2 :(得分:0)

这是一个巨大的依赖,但我个人喜欢Boost::Tokenizer

从页面上的示例:

// simple_example_1.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

int main(){
   using namespace std;
   using namespace boost;
   string s = "This is,  a test";
   tokenizer<> tok(s);
   for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){
       cout << *beg << "\n";
   }
}

答案 3 :(得分:-1)

只要涉及空白:

string s("somethin\nsomethingElse");
strinstream ss(s);
string line;
vector<string> lines;
while( ss >> line )
{
    lines.push_back( line );
}

或者,使用getline(),它允许您将标记字符指定为可选的第三个参数:

string s("Something\n\rOr\n\rOther");
stringstream ss(s);
vector<string> lines;
string line;
while( getline(ss,line) )
{
    lines.push_back(line);
}