我正在尝试反转字符串中的单词。
例子, 输入:as xsd bf 将导致输出:sa dsx fb。
我的问题是最后一个字没有反转。
例如,输入:as xsd bf 将导致输出:sa dsx bf。如您所愿看到 bf 没有被逆转。
我的代码,
#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;
}
最佳答案
你没有处理最后一个词,因为你在到达那里之前就停下来了:
while(wordEnd<inp.length()) { // When you finally get to the last letter. You will
// exit on the next loop iteration.
if(inp[wordEnd] != ' ')
你需要把它改成这样:
while(wordEnd<=inp.length()) {
if(wordEnd < inp.length() && inp[wordEnd] != ' ') {
//^ This is important so you dont go out of bounds on your string
关于c++ - 字符串中的最后一个单词不反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34074951/