C++中string小应用
来源:互联网 发布:js qq分享回调地址 编辑:程序博客网 时间:2024/06/06 15:44
/** 使用string实现字符串按单词反转* 如:olleH !dlrow => Hello world!*/#include <iostream>#include <string>#include <algorithm>#include <cstdlib>using namespace std;int main(int argc, char* argv[]){string str;while(getline(cin, str)){if(str.empty()) continue;string::iterator it_begin = str.begin();string::iterator it_end; //迭代器 for(it_end = str.begin(); it_end < str.end(); it_end++){if(*it_end == ' '){reverse(it_begin, it_end); //反转it_begin = it_end + 1;}}reverse(it_begin, it_end);cout<<str<<endl;}return 0;}
/** 统计回文串并按条件输出*/#include <iostream>#include <string>#include <algorithm>#include <vector>using namespace std;bool comp(string s1, string s2){ //用于排序的比较if(s1.length() != s2.length()){return s1.length() < s2.length();}return s1 < s2;}int main(int argc, char* argv[]){string str;vector<string> v_s;while(cin>>str){ //按ctrl+Z结束输入if(str.empty()) continue;string tmp = str;reverse(tmp.begin(), tmp.end());if(tmp == str){ //判断是否对称串v_s.push_back(str);}}sort(v_s.begin(), v_s.end(), comp); //利用比较函数排序vector<string>::iterator it; //迭代器for(it = v_s.begin(); it != v_s.end(); it++){cout<<*it<<endl;}return 0;}