New*_*ile 2 c++ string split words function
我试图用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;
}
Run Code Online (Sandbox Code Playgroud)
如果您只想显示字符串使用的单词:
#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"));
Run Code Online (Sandbox Code Playgroud)
其他处理这些词使用std::vector的std::string
std::vector<std::string> vec;
istringstream iss(test);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(vec));
Run Code Online (Sandbox Code Playgroud)