一、概述
案例:回顾string字符串相关操作。
二、代码示例
#include <iostream> #include <string> #include <vector> using namespace std; void test(){ string str; str = "luoluoyang"; str.assign("luoluoyang",3); cout << str<<endl; string str2; str2.assign(str); cout << str2<<endl; str2.assign(str,0,2); cout <<str2<<endl; } void test1(){ //字符串拼接 string str1 = "luoluoyang "; string str2 = "luoluoyang"; str1+=str2; cout<<str1<<endl; str1.append(" and tony son"); cout << str1<<endl; //查找字符串 string str = "Today is another beautiful day"; int pos = str.find("is"); if(pos==-1){ cout << "str not found"<<endl; }else{ cout << "str found is pos:"<<pos<<endl; } //替换 str.replace(1,5,"TTTTT"); cout<<str<<endl; string str3 = "hello world"; string str4 = "hello world"; //比较操作 if(str4.compare(str3)==0){ cout << "equals"<<endl; }else{ cout << "not equals"<<endl; } //查找子串 string strsub = str.substr(0,5); cout << strsub<<endl; // string email = "tony@163.com"; int pos2 = email.find("@"); string posStr = email.substr(0,pos2); cout << posStr<<endl; cout << "-----------------"<<endl; //解析字符串 string str5 = "www.baidu.compare"; vector<string> v; int start = 0; int pos3 = -1; while(true){ pos3 = str5.find(".",start); if(pos3==-1){ string tempstr = str5.substr(start,str5.size()-start); v.push_back(tempstr); break; } string tempstr = str5.substr(start,pos3-start); v.push_back(tempstr); start = pos3+1; } for(vector<string>::iterator it = v.begin();it!=v.end();it++){ cout << *it <<endl; } cout << "------------"<<endl; //插入字符 string str6 = "luoluoyang"; str6.insert(0,"222"); cout << str6<<endl; //删除字符 str6.erase(0,3); cout <<str6<<endl; //string和char *str相互转换 char *str7 = "tony"; string str8(str7); cout <<str8<<endl; string str9 = "kiki"; const char *str10 = str9.c_str(); cout << str10<<endl; } int main(int argc, char const *argv[]) { // test(); test1(); return 0; }