this split function works if passing a value fine, but if it is not passed a value sep, to auto split the string by whitespace. Its kind of doing it. It is adding an empty element into the vector. I am just not sure how to check for an empty element in c++ in order to avoid pushing that empty index to the back (line 21)? or to just re loop an remove, but that seems kind of redundant.
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
void split(const string s, vector<string> &v, char sep=NULL){
string index;
for (int i=0; i<s.length(); i++){
if (sep != NULL){
if (s[i] == sep){
v.push_back(index);
index = "";
}
else{
index += s[i];
}
}
else{
if (s[i] == ' ' || s[i] == '\t' || s[i] == '\n'){
v.push_back(index);
//std::cout << "element is: " << index << std::endl;
index = "";
}
else{
index += s[i];
}
}
}
v.push_back(index);
for (int i=0; i<s.length(); i++){
//remove empty elements
}
}
void print(vector<string> v){
for (int i=0; i<v.size(); i++){
cout << "[" << v[i] << "]";
}
}
int main(){
vector<string> v;
split("some random string sitting here", v,' ');
print(v);
std::cout << '\n';
vector<string> v2;
split("some random string\nsit\nting \t\t\n \n\there\n", v2);
print(v2);
}
1 2 3 4 5 6
test.cpp: In function ‘void split(std::string, std::vector<std::basic_string<char> >&, char)’:
test.cpp:10:20: warning: NULL used in arithmetic [-Wpointer-arith]
test.cpp: In function ‘int main()’:
test.cpp:48:66: warning: converting to non-pointer type ‘char’ from NULL [-Wconversion-null]
[some][random][string][sitting][here]
[some][random][string][sit][ting][][][][][][][][][here][]