使用istringstream
分割带有空格的字符串的以下技巧。
int main() {
string sentence("Cpp is fun");
istringstream in(sentence);
vector<string> vec = vector<string>(istream_iterator<string>(in), istream_iterator<string>());
return 0;
}
使用any
分隔符分割字符串是否有类似的技巧?例如,“Cpp | is | fun”中的|
。
答案 0 :(得分:20)
一般来说,istringstream方法速度慢/效率低,并且至少需要与字符串本身一样多的内存(当你有一个非常大的字符串时会发生什么?)。 C++ String Toolkit Library (StrTk)针对您的问题提供了以下解决方案:
#include <string>
#include <vector>
#include <deque>
#include "strtk.hpp"
int main()
{
std::string sentence1( "Cpp is fun" );
std::vector<std::string> vec;
strtk::parse(sentence1," ",vec);
std::string sentence2( "Cpp,is|fun" );
std::deque<std::string> deq;
strtk::parse(sentence2,"|,",deq);
return 0;
}
可以找到更多示例Here
答案 1 :(得分:5)
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::istringstream iss { "Cpp|is|fun" };
std::string s;
while ( std::getline( iss, s, '|' ) )
std::cout << s << std::endl;
return 0;
}
答案 2 :(得分:-1)
#include <iostream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>
using namespace std;
vector<string> splitter(string in_pattern, string& content){
vector<string> split_content;
regex pattern(in_pattern);
copy( sregex_token_iterator(content.begin(), content.end(), pattern, -1),
sregex_token_iterator(),back_inserter(split_content));
return split_content;
}
int main()
{
string sentence = "This|is|the|sentence";
//vector<string> words = splitter(R"(\s+)", sentence); // seperate by space
vector<string> words = splitter(R"(\|)", sentence);
for (string word: words){cout << word << endl;}
}
// we use regex to find the "|" and split the surrounding elements into an array. We then cout each of those elements in a for loop.
// This method allows for splitting with regex as an alternative