c++中string类的常用方法有哪些
导读:收集整理的这篇文章主要介绍了c++中string类的常用方法有哪些,觉得挺不错的,现在分享给大家,也给大家做个参考。c++中string类的常用方法如下:1、获取字符串长度 #include<cstdio>#include<...
收集整理的这篇文章主要介绍了c++中string类的常用方法有哪些,觉得挺不错的,现在分享给大家,也给大家做个参考。c++中string类的常用方法如下:
1、获取字符串长度
#includecstdio>
#includeiostream>
#includestring>
using namespace std;
int main(){
string str1 = "hello";
int length = str1.length();
PRintf("调用str.length()函数获取字符串长度:%d\n\n",length );
return 0;
}
2、字符串连接
#includecstdio>
#includeiostream>
#includestring>
using namespace std;
int main(){
string str1 = "hello";
string str2="my girl!";
string str3="hello ";
string str4=str1+str2;
string str5=str3+str2;
cout"字符串str1+str2连接结果:"str4endl;
coutendl;
cout"字符串str3+str2连接结果:"str5endl;
return 0;
}
3、字符串比较
#includecstdio>
#includeiostream>
#includestring>
using namespace std;
int main(){
string str1 = "hello";
string str2="my girl!";
string str3="hello ";
if (str1 str3) cout "字符串比较结果:" "str1str2" endl;
cout endl;
return 0;
}
4、字符串转字符数组
#includecstdio>
#includeiostream>
#includestring>
#includecstring>
using namespace std;
int main(){
string str1 = "hello";
string str2="my girl!";
string str3="hello ";
char *d = new char[20];
//因为下一句那里不是直接赋值,所以指针类型可以不用const char * strcpy(d, str3.c_str());
//c_str 取得C风格的const char* 字符串 cout "str3:" c endl;
cout "d:" d endl;
str3 = "hahaha";
cout "str3:" c endl;
cout "d:" d endl;
return 0;
}
推荐教程:c语言教程
以上就是c++中string类的常用方法有哪些的详细内容,更多请关注其它相关文章!
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c++中string类的常用方法有哪些
本文地址: https://pptw.com/jishu/594128.html
