Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue
“,
return “blue is sky the
“.
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 }
TIPS:
LINE9 ,不可用s.push_back。因为string相当于一个字符的容器,push_back的参数只能是字符
LINE11: substr并不改变string,返回值为string
转载于//www.cnblogs.com/nnoth/p/3742634.html
还没有评论,来说两句吧...