-2

I am trying to split a char* based on a delimiter using nested vectors however the last word of the char* seems to not be added to the vector>

vector<vector<char>> split(char* word, const char de){
    vector<vector<char>> words;
    vector<char> c_word;
    while(*word){
        if(*word == de){
            words.push_back(c_word);
            c_word.clear();
            word++;
            continue;
        }
        c_word.push_back(*word);
        word++;
    }
    return words;
}

Example usage:

int main() {
    char *let = "Hello world!";

    vector<vector<char>> words = split(let, ' ');
    for(int x = 0;x < words.size();x++){
        for(int y = 0;y < words[x].size();y++){
            cout << words[x][y];
        }
        cout << endl;
    }
}

This would print only Hello

MartinStone
  • 184
  • 1
  • 2
  • 14

2 Answers2

-1

Here is a full working code with multiple delimeters

vector<vector<char>> split(char* word, const char de) {
    vector<vector<char>> words;
    vector<char> c_word;
    int index = 0;
    int j = 0;
    char *temp = word;
    int numspaces = 0;
    while (*word) {
        if (*word == de) {
            words.push_back(c_word);
            c_word.clear();
            word++;
            j = index;
            numspaces++;
        }
        index++;
        c_word.push_back(*word);
        word++;
    }
    j +=numspaces;
    char *sub = &temp[j];
    c_word.clear();
    while (*sub)
    {
        c_word.push_back(*sub);
        sub++;
    }
    words.push_back(c_word);
    return words;
}
void main()
{
    vector<vector<char>> result = split("Hello World! Ahmed Saleh", ' ');

}
andre_lamothe
  • 2,171
  • 2
  • 41
  • 74
-2

For anyone else wondering how to do this implementation using char* instead of string. What my code is missing is a final add of c_word to words since the while is already over when it reaches the null terminator and doesn't add the final word, this is the fixed code:

   vector<vector<char>> split(char* word, const char de){
    vector<vector<char>> words;
    vector<char> c_word;
    while(*word){
        if(*word == de){
            words.push_back(c_word);
            c_word.clear();
            word++;
            continue;
        }
        c_word.push_back(*word);
        word++;
    }
    words.push_back(c_word);
    return words;
}
MartinStone
  • 184
  • 1
  • 2
  • 14