3

我试图在 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;


}
4

1 回答 1

10

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

#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 来处理这些词std::vector的用途std::string

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

        istringstream iss(test);
        copy(istream_iterator<string>(iss),
                 istream_iterator<string>(),
                 back_inserter(vec));
于 2013-10-02T13:07:52.977 回答