即時嘗試在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