正如在評論中提到的,有很多更方便的方法來拆分字符串(strtok
,std功能等),但如果我們談論你的示例,你不應該分配'str [我]」但附加它,因爲它是要追加到當前的字像這樣的單個字符:
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;
for(short i=0;i<str.length();i++){
if(str[i] == ' ' && !strWords[counter].empty()){
counter++;
}
else {
strWords[counter] += str[i];
}
}
但這將只在給定的輸入數據,因爲你可以訪問陣列strWords
如果你有五個以上的單詞,那就是外部界限。請考慮使用以下代碼:
string str = "Welcome to the computer world.";
vector<string> strWords;
string currentWord;
for(short i=0;i<str.length();i++){
if(str[i] == ' ' && !currentWord.empty()){
strWords.push_back(currentWord);
currentWord.clear();
}
else {
currentWord += str[i];
}
}
UPDATE
因爲我認爲你是新的C++,這裏是你(如果你只使用加法運算)的空間問題的演示:
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;
for(short i=0;i<str.length();i++){
strWords[counter] += str[i]; // Append fixed
if(str[i] == ' '){
counter++;
}
}
for(short i=0;i<5;i++){
cout << strWords[i] << "(" << strWords[i].size() << ")" << endl;
}
return 0;
}
結果:
可能的重複[如何在C++中拆分字符串?](http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c) – CoryKramer 2014-10-17 12:18:55
也是http:// stackoverflow。 com/questions/8448176/split-a-string-into-an-array-in -c – CoryKramer 2014-10-17 12:19:12
@Cyber:我的問題與你認爲我的問題與他們相似的問題略有不同。 – 2014-10-17 12:29:07