今天发现自己不怎么会用C++ String
1:String的创建
string str1 ="abcd"
string str2;str2="abcd";//本方法调用拷贝构造函数
string str3("abcd");
string str4(4,'x');//用4个字符初始化
string str5("ILOVELUOGU",1,4);//类似于截取
C++ string和py不同 C++是从0开始 没反向序号
2:C++string和C语言char*区别:
C++ string中有size和length函数来判断当前字符串长度
C++ string访问不能直接用printf 需要用data(),c_str()
printf("%st%sn",str2.data(),str2.c_str())
3 :基本操作(增删改查)
3.1 c++string的赋值方式:
通过函数assign
#include#includeusing namespace std;int main(){string s1("IMISSYOU");string s2;s2.assign(s1);}
#include#includeusing namespace std;int main(){string s1("IMISSYOU");string s2;s2.assign(s1,1,4);}
#include#includeusing namespace std;int main(){string s1("IMISSYOU");string s2;s2.assign(4,'k');}
3.2 比较
直接用运算符去比较,返回布尔类型
#include#includeusing namespace std;int main(){string first = "123";string second = "23";cout<<(first>second)<
调用成员函数
compare
#include#includeusing namespace std;int main(){string first = "123";string second = "23";cout<
3.3字符串连接
直接用加法
#include#includeusing namespace std;int main(){string first = "123";string second = "23";cout<
通过函数append(可以更灵活连接)
#include#includeusing namespace std;int main(){string first = "123";string second = "23";first.append(second);return 0;}
3.3 C++string查找
find:从左往右找,找子串or字符 返回string::npos(-1)
#include#includeusing namespace std;int main(){string findstr("Iloveyou,Imissyou");if(findstr.find('o')!=string::npos) cout<
#include#includeusing namespace std;int main(){string findstr("Iloveyou,Imissyou");if(findstr.rfind('o')!=string::npos) cout<
find_first_of:查找第一次出现的字串
#include#includeusing namespace std;int main(){string findstr("Iloveyou,Imissyou");if(findstr.find_first_of("you")!=string::npos) cout<
子串:要找字符串的任意一个字符
find_first_not_of:第一次不是字串的位置
从右往左:find_last_of:功能和上面一样
3.4替换 replace
#include#includeusing namespace std;int main(){string r1str("Iloveyou,Imissyou");r1str.replace(1,4,"miss");cout<