c++ - 字符串中的最后一个单词不反转

标签 c++ string

我正在尝试反转字符串中的单词。

例子, 输入: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

Here is a live example.

关于c++ - 字符串中的最后一个单词不反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34074951/

相关文章:

c++ - C++ 中逗号分隔的 float

c++ - 什么是不透明字节串?

c++ - 访问 char* 或 std::string 的元素是否更快?

python - 运算符优先级对字符串的工作方式与对数字的工作方式相同吗?

c++ - 大量对象的极端内存使用

python - 指向外部托管的 C++ 智能指针(例如 : Python) resources?

c++ - 如何使快速排序算法中已排序数组的交换次数为零?

c++ - 处理命令行参数,允许任何顺序

C弦长

java - 替换字符串并检查字符串内的唯一性