C ++函数将字符串拆分为单词

时间:2013-10-02 13:04:46

标签: c++ string function split words

我试图在c ++中编写一个函数,将我的字符串测试拆分为数组中的单独单词。我似乎无法循环中的东西......任何人有任何想法?它应该打印“这个”

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;


}

1 个答案:

答案 0 :(得分:9)

如果您只想显示字符串使用的单词:

#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"));

要处理这些字词,请使用std::vector

std::string
     std::vector<std::string> vec;

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