2014-10-17 64 views
0

我有一個句子,我想拆分句子以便在數組項中添加每個單詞。
我已經做了下面的代碼,但它仍然是錯誤的。拆分句子,以便將每個單詞添加到數組項中

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

可能的重複[如何在C++中拆分字符串?](http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c) – CoryKramer 2014-10-17 12:18:55

+0

也是http:// stackoverflow。 com/questions/8448176/split-a-string-into-an-array-in -c – CoryKramer 2014-10-17 12:19:12

+0

@Cyber​​:我的問題與你認爲我的問題與他們相似的問題略有不同。 – 2014-10-17 12:29:07

回答

2

我回答,因爲你應該從錯誤中學習:只使用+=字符串操作,你的代碼將工作:

// strWords[counter] = str[i]; <- change this 
strWords[counter] += str[i];  <- to this 

把空格去掉(如果你不希望他們追加)只是改變了空間檢查的順序,是這樣的:

for (short i = 0; i<str.length(); i++){ 
    if (str[i] == ' ') 
     counter++; 
    else 
     strWords[counter] += str[i]; 
} 

反正我建議使用複製鏈接Split a string in C++?

+1

謝謝你,你的答案是最簡單的答案。 – 2014-10-17 12:35:10

+1

@LionKing你知道你會在每個單詞後面添加句子中的空格,因爲你只有在你添加了字符到當前單詞之後才檢查空格嗎? – 2014-10-17 12:39:29

+0

@RudolfsBundulis:謝謝你的建議。但是我沒有看到每個單詞都有空格。 – 2014-10-17 12:59:00

1

非常醜陋的做法,@Cyber​​鏈接到最好的答案。但是,這裏是你的「修正」版本:

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]; 
} 
0

正如在評論中提到的,有很多更方便的方法來拆分字符串(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; 
} 

結果:

Space at the end of each string

+0

我也感謝你的回答和澄清。 – 2014-10-17 14:52:22

相關問題