拆分子字符串 [英] Split on substring

查看:140
本文介绍了拆分子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如。拆分为\r\\\

  message1 \r\\\
message2

=>

  message1 
message2



从我已经能够找到boost :: tokenizer和boost :: split



我知道我可以这样做通过使用std :: string :: find和std :: string :: substr并且有一个循环等...但这不是我的意思是简单。

解决方案

虽然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<< '\\\
';
}


How would I split a string based on another substring in a simple way?

e.g. split on "\r\n"

message1\r\nmessage2 

=>

message1
message2

From what I've been able to find both boost::tokenizer and boost::split only operates on single characters.

EDIT:

I'm aware that I could do this by using std::string::find and std::string::substr and have a loop etc... but thats not what I mean by "simple".

解决方案

Although boost::split indeed takes a predicate that operates on characters, there's a boost string algorithm that can split on substrings:

#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';
}

这篇关于拆分子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆