std::string
is more safer than your method like chris mentioned as a comment.
For your learning:
#include <iostream>
#include <string>
int main() {
std::string s = "ALEX#19#INDIA";
std::string delimiter = "#";
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;
return 0;
}
What I do if I need like the code
#include <string>
#include <vector>
#include <functional>
#include <iostream>
void split(const std::string& s, char c,
std::vector<std::string>& v) {
std::string::size_type i = 0;
std::string::size_type j = s.find(c);
while (j != std::string::npos) {
v.push_back(s.substr(i, j-i));
i = ++j;
j = s.find(c, j);
if (j == std::string::npos)
v.push_back(s.substr(i, s.length()));
}
}
int main() {
std::vector<std::string> v;
std::string s = "ALEX#19#INDIA";
char delimiter = '#';
split(s, delimiter, v);
for (auto& i : v) {
std::cout << i << '\n';
}
}