How to split a string according to "|"

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?
| is a character with special meaning in regular expressions; we need to escape it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <vector>
#include <regex>

std::vector<std::string> s_split( const std::string& in, const std::string& delim ) {

    const std::regex re{delim} ;

    return {
               std::sregex_token_iterator( in.begin(), in.end(), re, -1 ),
               std::sregex_token_iterator()
           };
}

int main()
{
    for( const auto& tok : s_split( "AAAAA|BBBBB|CCCCC", "\\|" ) ) std::cout << tok << '\n' ;
}

http://coliru.stacked-crooked.com/a/e80a2bbe3f6e916d
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
@JLBorges why use double "\"
> why use double "\"

In a C++ literal, \ is an escape character.
So '\\' results a single backslash character.
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';
}



AAAAA
BBBBB

CCCCC

Last edited on
Topic archived. No new replies allowed.