首页 > 其他 > 详细

Reverse Words in a String

时间:2014-05-23 02:59:04      阅读:369      评论:0      收藏:0      [点我收藏+]

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

 

bubuko.com,布布扣
 1 Class Solution{
 2 public:    
 3    void reverseWords(string &s){
 4        char c[1]={ };
 5        vector<string> slist  = split(s,c);
 6        reverse(slist.begin(),slist.end());
 7        s.clear();
 8        for(int i = 0 ; i < slist.size(); ++i){
 9               s = s + slist[i] + " ";
10        }    
11        s = s.substr(0,s.size()-1);  
12   } 
13     vector<string> split(string &s, const char* c){
14          char *p;
15          vector<string> rst;
16          char *cstr = new char[s.length()+1];
17          strcpy(cstr,s.c_str());
18          p = strtok(cstr,c);
19          while(p){
20              rst.push_back(p);
21              p = strtok(NULL,c);
22          } 
23          return rst;
24     }
25 }             
bubuko.com,布布扣

 

TIPS:

1. LINE9 ,不可用s.push_back。因为string相当于一个字符的容器,push_back的参数只能是字符

2. LINE11: substr并不改变string,返回值为string

 

 

Reverse Words in a String,布布扣,bubuko.com

Reverse Words in a String

原文:http://www.cnblogs.com/nnoth/p/3742634.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!