c++中string類的常用方法如下:
1、獲取字符串長(zhǎng)度
#include<cstdio> #include<iostream> #include<string> using namespace std; int main() { string str1 = "hello"; int length = str1.length(); printf("調(diào)用str.length()函數(shù)獲取字符串長(zhǎng)度:%dnn",length ); return 0; }
2、字符串連接
#include<cstdio> #include<iostream> #include<string> 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連接結(jié)果:"<<str4<<endl; cout<<endl; cout<<"字符串str3+str2連接結(jié)果:"<<str5<<endl; return 0; }
3、字符串比較
#include<cstdio> #include<iostream> #include<string> using namespace std; int main() { string str1 = "hello"; string str2="my girl!"; string str3="hello "; if (str1 < str3) cout << "字符串比較結(jié)果:" << "str1<str2" << endl; cout << endl; return 0; }
4、字符串轉(zhuǎn)字符數(shù)組
#include<cstdio> #include<iostream> #include<string> #include<cstring> using namespace std; int main() { string str1 = "hello"; string str2="my girl!"; string str3="hello "; char *d = new char[20]; //因?yàn)橄乱痪淠抢锊皇侵苯淤x值,所以指針類型可以不用const char * strcpy(d, str3.c_str()); //c_str 取得C風(fēng)格的const char* 字符串 cout << "str3:" << c << endl; cout << "d:" << d << endl; str3 = "hahaha"; cout << "str3:" << c << endl; cout << "d:" << d << endl; return 0; }
推薦教程:c語(yǔ)言教程