-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit_a_string.cpp
More file actions
52 lines (42 loc) · 1.11 KB
/
split_a_string.cpp
File metadata and controls
52 lines (42 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>
#include <vector>
struct TokenPosition
{
size_t start;
size_t end;
};
static std::vector<TokenPosition>
SplitString(const std::string& input_string, const std::string& delimiters)
{
std::vector<TokenPosition> tokens;
size_t start = 0, end = input_string.find_first_of(delimiters);
while (end != std::string::npos)
{
if (end > start)
{
tokens.push_back({ start, end });
}
start = end + 1;
end = input_string.find_first_of(delimiters, start);
}
if (start < input_string.length())
{
tokens.push_back({ start, input_string.length() });
}
return tokens;
}
int main()
{
std::string input, delimiters;
std::cout << "Enter the string: ";
std::getline(std::cin, input);
std::cout << "Enter the delimiter characters: ";
std::getline(std::cin, delimiters);
auto tokens = SplitString(input, delimiters);
for (const auto& tokenPos : tokens)
{
std::cout << input.substr(tokenPos.start, tokenPos.end - tokenPos.start) << std::endl;
}
return 0;
}