首页 > 代码库 > Reverse Words in a String
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:
1. LINE9 ,不可用s.push_back。因为string相当于一个字符的容器,push_back的参数只能是字符
2. LINE11: substr并不改变string,返回值为string
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。