2015-12-03 24 views
0

我正在嘗試將字符串中的單詞逆轉。字符串中的最後一個字不能逆轉

實施例, 輸入:爲XSD BF將導致輸出:SA DSX FB

我的問題是,最後一個字不會逆轉。

例,輸入:爲XSD BF會導致輸出:SA DSX BF。正如你所看到的BF沒有得到扭轉。

while(wordEnd<inp.length()) { // When you finally get to the last letter. You will 
           // exit on the next loop iteration. 
    if(inp[wordEnd] != ' ') 

你需要把它改成這樣:

我的代碼,

#include<iostream> 
#include<string> 
using namespace std; 

void RevWords(string inp); 


int main() 
{ 
    string input; 

    cout<<"Enter Sring:"<<endl; 
    getline(cin,input); 
    cout<<"Entered String:"<<input<<endl; 
    RevWords(input); 

    return 0; 
} 

void RevWords(string inp) 
{ 
    int wordEnd=0,indexS=0,indexE=0; 
    string newStr; 
    newStr=inp; 

    while(wordEnd<inp.length()) 
    { 
     if(inp[wordEnd] != ' ') 
     { 
     wordEnd++; 
     } 
     else 
     { 
     if(inp[wordEnd] == ' ' || inp[wordEnd] == '\0') 
     { 
      indexE=wordEnd-1; 
      while(indexS<wordEnd) 
      { 
       newStr[indexS]=inp[indexE]; 
       indexS++; 
       indexE--; 
      } 
      newStr[indexS]=' '; 
      indexS++; 
     } 
     wordEnd++; 
     }  
    } 
    cout<<newStr<<endl; 
} 
+4

T在調試代碼時,這是理解正在發生的事情的最佳方式。 – Motti

+0

你忘了問一個問題。你的問題是,「你如何調試C++代碼?」如果是這樣,爲什麼給我們所有的代碼,而不是告訴我們你有什麼調試器? –

+3

對單詞矢量的每個元素使用'std :: reverse',爲什麼這些都是? – LogicStuff

回答

1

因爲你停止你以前有你不處理的最後一個字

while(wordEnd<=inp.length()) { 
    if(wordEnd < inp.length() && inp[wordEnd] != ' ') { 
     //^ This is important so you dont go out of bounds on your string 

Here is a live example.

+0

回覆:你的演示:單詞稍縱即逝* AndyG

+0

非常感謝。是的,我忘了那個長度不包括空終止符。爲了提醒我,我感謝Ben和BeyelerStudios。而且我也感謝Ben提醒我這個詞End LuckyAli

+0

@AndyG這是拼寫不是語法;)謝謝,雖然我會改變它。 –

相關問題