即时尝试在C++中编写一个函数,将我的字符串测试分割成数组中的单独单词。我似乎不能在循环中的东西...任何人有任何想法?它应打印“这个”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;
}
std::vector
这是怎么样的重新发明轮子。为什么不使用字符串流的默认行为? – Danstahr有两点意见:(a)什么阻止你自己调试它? (你知道如何使用调试器,对吗?)和(b)如果这应该是C++,那么为什么要使用裸指针和C风格的编程呢? –
sizeof(tempLine)等效于在x86架构中使用4(32位)的sizeof(char *)。你可以使用strlen(tempLine)获取字符串的长度。另外我建议你使用std :: vector而不是原始char []数组。 –
dacap