我正在嘗試將字符串中的單詞逆轉。字符串中的最後一個字不能逆轉
實施例, 輸入:爲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;
}
T在調試代碼時,這是理解正在發生的事情的最佳方式。 – Motti
你忘了問一個問題。你的問題是,「你如何調試C++代碼?」如果是這樣,爲什麼給我們所有的代碼,而不是告訴我們你有什麼調試器? –
對單詞矢量的每個元素使用'std :: reverse',爲什麼這些都是? – LogicStuff