![](/img/trans.png)
[英]split a string using multiple delimiters (including delimiters) in c++
[英]Split string using multiple string delimiters
假設我有字符串
Harry potter was written by J. K. Rowling
如何使用was
和by
作為分隔符拆分字符串並在C ++中獲取vector中的結果?
我知道使用多個char但不使用多個字符串進行拆分。
如果你使用c ++ 11和clang,有一個使用正則表達式字符串標記器的解決方案:
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <regex>
int main()
{
std::string text = " Harry potter was written by J. K. Rowling.";
std::regex ws_re("(was)|(by)");
std::copy( std::sregex_token_iterator(text.begin(), text.end(), ws_re, -1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
輸出是:
Harry potter
written
J. K. Rowling.
可悲的是gcc4.8沒有正則表達式完全集成。 但clang確實可以正確編譯和鏈接。
蠻力方法,而不是提升,沒有c ++ 11,優化超過歡迎:
/** Split the string s by the delimiters, place the result in the
outgoing vector result */
void split(const std::string& s, const std::vector<std::string>& delims,
std::vector<std::string>& result)
{
// split the string into words
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> splits(begin, end);
// then append the words together, except if they are delimiter
std::string current;
for(int i=0; i<splits.size(); i++)
{
if(std::find(delims.begin(), delims.end(), splits[i]) != delims.end())
{
result.push_back(current);
current = "";
}
else
{
current += splits[i] + " " ;
}
}
result.push_back(current.substr(0, current.size() - 1));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.