在STL里面string的应用:
代码测试:(只是一步步的简单应用)
#include <iostream> #include <string> using namespace std; int main() { cout<<"输出一个字符串:"<<endl; string s1 = "hello"; cout<<s1<<endl; cout<<"输出在一个迭代器的位置插入n个字符后的字符串"<<endl; s1.insert(0,1,'W'); s1.push_back('Q');//类似vector在末尾插入 /** 在string中不能使用front,back,pop_back操作 */ s1.insert(s1.begin(),1,'a'); cout<<s1<<endl; cout<<"在pos位置插入,输出一个区间"<<endl; s1.insert(s1.begin()+2,s1.begin(),s1.end()); cout<<s1<<endl; cout<<"输出替换的字符容器"<<endl; s1.assign(10,'x'); cout<<s1<<endl; cout<<"string也是支持string[],string.at(i)"<<endl; cout<<"string[] 不会抛出越界异常,string会抛出越界异常"<<endl; //cout<<s1[1]<<"=-"<<s1.at(15)<<endl; cout<<"字符容器可以直接使用常量来进行替换"<<endl; cout << s1.assign("hello") << endl; string s2 = "world"; cout<<"俩个拼接字符串"<<endl; //cout<<s1+s2<<endl; s2.insert(s2.begin(),s1.begin(),s1.end()); cout<<s2<<endl; cout<<"在末尾插入"<<endl; s2.insert(s2.size(),5,'!'); cout<<s2<<endl; cout<<"删除末尾的5个字符"<<endl; s2.erase(s2.size()-5,5); cout<<s2<<endl; /** 只适用于string的操作 下标使用数字,不适用迭代器 .begin() ... .end() substr函数 append函数 replace函数 这几个函数输入的是字符串不是字符 */ cout<<"返回s3的字串,s2的字串不变"<<endl; string s3; s3 = s2.substr(0,3);//只能使用数字下标 不能使用迭代器.begin()函数 //cout<<s2<<endl; cout<<s3<<endl; string s4 = s3.substr(); cout<<s4<<endl; cout<<"追加后的字符串:"<<endl; s4.append("abcd"); cout<<s4<<endl; cout<<"输出从下标0-3的字符串被替换后的字符串"<<endl; s4.replace(0,3,"x"); cout<<s4<<endl; cout<<"返回找到字符串的下标位置:0~n"<<endl; cout<<s4.find("a")<<endl; cout<<s4.find_first_not_of("a")<<endl; cout<<s4.find_first_of("a")<<endl; cout<<s4.find_last_not_of("a")<<endl; cout<<s4.find_last_of("a")<<endl; cout<<"输出比较字符串的值:"<<endl; /** s5 > s6 返回正数 s5 == s6 返回0 s5 < s6 返回负数 */ string s5 = "hello"; string s6 = "hell"; cout<<s6.compare(s6)<<endl; return 0; }
原文:http://blog.csdn.net/xd_122/article/details/44649467