split a sentence so that adds each word in an array item
我有一个句子,我想拆分这个句子,以便在一个数组项中添加每个单词。我已经做了以下代码,但它仍然是错误的。
1 2 3 4 5 6 7 8 9 | 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]; if(str[i] == ' '){ counter++; } } |
我的回答是,您应该从错误中吸取教训:只要使用
1 2 | // strWords[counter] = str[i]; <- change this strWords[counter] += str[i]; <- to this |
要删除空格(如果不想附加空格),只需更改空格检查的顺序,如下所示:
1 2 3 4 5 6 | for (short i = 0; i<str.length(); i++){ if (str[i] == ' ') counter++; else strWords[counter] += str[i]; } |
无论如何,我建议使用重复链接在C++中分割一个字符串?太
做这件事的方式非常丑陋,@cyber已经找到了最好的答案。但这是你的"修正"版本:
1 2 3 4 5 6 7 8 9 10 11 | string str ="Welcome to the computer world."; string strWords[5]; short counter = 0; for(short i=0;i<str.length();i++){ if(str[i] == ' '){ counter++; i++; } strWords[counter] += str[i]; } |
正如注释中所提到的,拆分字符串有很多更方便的方法(
1 2 3 4 5 6 7 8 9 10 11 | 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]; } } |
但这只对给定的输入数据有效,因为如果您有五个以上的字,您可以访问数组
1 2 3 4 5 6 7 8 9 10 11 12 | 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]; } } |
更新
因为我假设你是C++的新手,所以这里有一个空间问题的演示(如果你只使用加法运算符):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #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; } |
结果: