码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Words in a String

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

标签:style   class   blog   c   code   java   

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

标签:style   class   blog   c   code   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!