本文摘自PHP中文网,作者V,侵删。

c++中string类的常用方法如下:
1、获取字符串长度
1 2 3 4 5 6 7 8 9 10 11 12 | # include <cstdio>
# include <iostream>
# include <string>
using namespace std;
int main()
{
string str1 = "hello" ;
int length = str1.length();
printf( "调用str.length()函数获取字符串长度:%d\n\n" ,length );
return 0;
}
|
2、字符串连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # 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连接结果:" <<str4<<endl;
cout<<endl;
cout<< "字符串str3+str2连接结果:" <<str5<<endl;
return 0;
}
|
3、字符串比较
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # 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 << "字符串比较结果:" << "str1<str2" << endl;
cout << endl;
return 0;
}
|
4、字符串转字符数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | # 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];
strcpy(d, str3.c_str());
cout << "str3:" << c << endl;
cout << "d:" << d << endl;
str3 = "hahaha" ;
cout << "str3:" << c << endl;
cout << "d:" << d << endl;
return 0;
}
|
推荐教程:c语言教程
以上就是c++中string类的常用方法有哪些的详细内容!
相关阅读 >>
C++输出二维字符矩阵对齐
简单工厂factory
第六章C++:函数基础与应用
C++基础知识
如何安装visual C++ 6.0
C++中类的定义是什么
C++文件怎么进行读取和写入操作
vC++和C++之间有什么区别?
C++标识符命名规则
如何用C++读取ini文件中的section节名
更多相关阅读请进入《C++》频道 >>
转载请注明出处:木庄网络博客 » c++中string类的常用方法有哪些