Friday, July 23, 2021

Split a string by a given delimiter

 I was really amazed to find out that C++ string class has no split method. There are plenty of accasions I needed to split a string by a given delimiter. Lets see how to split a string and put substrings in a to vector. 

vector<string> split(const string &str, const char delim) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(delim, start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
view raw split.cpp hosted with ❤ by GitHub
If you think incrementing varable start is ugly, you can use function find_first_not_of for it
vector<string> split(const string &str, const char delim) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((start = str.find_first_not_of(delim, end)) != string::npos) {
end = str.find(delim, start);
tokens.push_back(str.substr(start, end - start));
}
return tokens;
}
view raw split2.cpp hosted with ❤ by GitHub

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...