需要一个程序来反转字符串中的单词 [英] Need a program to reverse the words in a string

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

问题描述

我在几次采访中问了这个问题.我想从 Stackoverflow 读者那里知道这个问题的答案应该是什么.

I asked this question in a few interviews. I want to know from the Stackoverflow readers as to what should be the answer to this question.

这样一个看似简单的问题,却有很多不同的解释.

Such a seemingly simple question, but has been interpreted quite a few different ways.

推荐答案

如果你还想考虑空格,你可以这样做:

If you want to take into consideration also spaces, you can do it like that:

   string word = "hello    my name   is";
   string result="";
   int k=word.size();
   for (int j=word.size()-1; j>=0; j--)
   {       
       while(word[j]!= ' ' && j>=0)
           j--;

       int end=k;
       k=j+1;
       int count=0;
       if (j>=0)  
       {        
           int temp=j;
           while (word[temp]==' '){
               count++;
               temp--;           
           }           
           j-=count;
       }        
       else j=j+1;       

       result+=word.substr(k,end-k);
       k-=count;
       while(count!=0)
       {
           result+=' ';
           count--;
       }
   }  

它会为你打印出来is name my hello"

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

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