本文摘自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++中main函数的返回值类型是什么
C++如何实现字符串分割函数split?(代码示例)
详解C++虚成员函数和动态联编
C++中string的用法介绍
C++的可移植性和跨平台开发(长文)
第五章C++:语句的相关介绍
新手程序员应该知道的c语言和C++的区别
第一章C++:函数返回值、gnu编译器命令
C++笔试题之实现简单记录错误功能
C++是面向对象还是面向过程?
更多相关阅读请进入《C++》频道 >>
转载请注明出处:木庄网络博客 » c++中string类的常用方法有哪些