Search code examples
c++stringfunctionsplitwords

C++ function split string into words


im trying to write a function in c++ that splits my string test into separate words in an array. i cant seem to the stuff in loop right... anyone got any ideas? it should print "this"

void app::split() {

    string test = "this is my testing string.";

    char* tempLine = new char[test.size() + 1];
    strcpy(tempLine, test.c_str());

    char* singleWord;

    for (int i = 0; i < sizeof(tempLine); i++) {

        if (tempLine[i] == ' ') {
            words[wordCount] = singleWord;
            delete[]singleWord;
        }

            else {
            singleWord[i] = tempLine[i];
            wordCount++;

            }

    }

    cout << words[0];
    delete[]tempLine;


}

Solution

  • If you just want to display words from string use:

    #include <algorithm>
    #include <iterator>
    #include <sstream>
    //..
       string test= "this is my testing string.";
            istringstream iss(test);
            copy(istream_iterator<string>(iss),
                     istream_iterator<string>(),
                     ostream_iterator<string>(cout, "\n"));
    

    else to process those words uses std::vector of std::string

         std::vector<std::string> vec;
    
            istringstream iss(test);
            copy(istream_iterator<string>(iss),
                     istream_iterator<string>(),
                     back_inserter(vec));