我试图用c ++编写一个函数,将我的字符串测试分成数组中的单独单词。我似乎无法正确循环...任何人有任何想法吗?它应该打印“ 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;
}
如果只想显示字符串中的单词,请使用:
#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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句