【发布时间】:2013-10-02 13:04:46
【问题描述】:
我试图在 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;
}
【问题讨论】:
-
这是一种重新发明轮子。为什么不使用字符串流的默认行为?
-
两个 cmets:(a) 是什么阻止你自己调试这个? (你知道如何使用调试器,对吧?)和 (b) 如果这应该是 C++,那么为什么要使用裸指针和 C 风格的编程?
-
sizeof(tempLine) 等价于使用 x86 架构中的 4(32 位)sizeof(char*)。您可以使用 strlen(tempLine) 获取字符串的长度。另外,我建议您使用 std::vector
而不是原始 char[] 数组。 -
你也可以使用 string::substr() 函数来获取原始字符串的一部分。
-
您想学习基础知识(例如数组和指针)还是高级功能(例如标准容器和
stringstream)?
标签: c++ string function split words