字符串中的最后一个字词不是反转 [英] The last word in a string is not reversing

查看:81
本文介绍了字符串中的最后一个字词不是反转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图颠倒字符串中的单词。

I am trying to reverse the words in a string.

示例,
输入: as xsd bf 会导致输出: sa dsx fb

Example, Input:as xsd bf would result in Output:sa dsx fb.

我的问题是,

例如输入:为xsd bf 会导致输出: sa dsx bf 。如您所见,bf不会被撤销。

Example,Input:as xsd bf would result in Output:sa dsx bf.As you can see bf doesn't get reversed.

我的代码,

#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;
}


推荐答案

最后一个字,因为在你到达之前停止:

You don't handle the last word because you stop before you get there:

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

您需要将其更改为这个:

You need to change it to this:

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

这是实例。

这篇关于字符串中的最后一个字词不是反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆