Jul 5, 2022 at 2:51am Jul 5, 2022 at 2:51am UTC
hello everyone,
I have a problem with split in c++11,this is my code in main:
string str = "AAAAA|BBBBB|CCCCC";
vector<string> vec = s_split(str,"|");
for(auto i : vec){
cout<<i<<" "<<endl;
}
and this is s_spilt():
vector<string> s_split(const string& in, const string& delim) {
regex re{ delim};
return vector<string> {
sregex_token_iterator(in.begin(), in.end(), re, -1),
sregex_token_iterator()
};
}
The output is one character one split,Why?
Jul 5, 2022 at 3:47am Jul 5, 2022 at 3:47am UTC
I try this code:
vector<string> vec = s_split(str,"\|");
it still has this problem,then I try
vector<string> vec = s_split(str,R"(\|)");
Successfully resolved
Jul 5, 2022 at 3:50am Jul 5, 2022 at 3:50am UTC
@JLBorges why use double "\"
Jul 5, 2022 at 3:58am Jul 5, 2022 at 3:58am UTC
> why use double "\"
In a C++ literal, \ is an escape character.
So '\\ ' results a single backslash character.
Jul 6, 2022 at 3:44pm Jul 6, 2022 at 3:44pm UTC
Using C++20 ranges:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <vector>
#include <ranges>
#include <iostream>
#include <string>
namespace rngs = std::ranges;
using namespace std::string_literals;
auto split(const std::string& str, char delm) {
std::vector<std::string> words;
for (const auto & word : rngs::split_view(str, delm))
words.emplace_back(word.begin(), word.end());
return words;
}
int main() {
const auto str { split("AAAAA|BBBBB||CCCCC" s, '|' )};
for (const auto & s : str)
std::cout << s << '\n' ;
}
Last edited on Jul 6, 2022 at 3:45pm Jul 6, 2022 at 3:45pm UTC