使用 string 类需要包含头文件<string>
,下面的例子介绍了几种定义 string 变量(对象)的方法:
#include#include using namespace std;int main(){ string s1; // 只定义不初始化,编译器会赋默认值,默认值为"",即空字符串 string s2 = "C Plus Plus"; // 既定义又初始化,与C风格字符串不同,string结尾没有结束标志'\0' string s3 = s2; // s3定义时使用s2进行初始化,因此s3内容也是"C Plus Plus" string s4 (5,'s'); // s4被初始化由5个's'字符组成的字符串,也就是"sssss" return 0;}
一.length() 返回字符串长度
string s = "http://www.iosfan.cn";int len = s.length();cout<<
注意: 与C不同,string末尾没有'\0'字符,所以length返回的是字符串的真实长度,而不是长度+1
二.c_str() 转换为C风格的字符串
string path = "D:\\demo.txt";FILE *fp = fopen(path.c_str(), "rt");
三.访问字符串中的字符
#include#include using namespace std;int main(){ string s = "1234567890"; for(int i=0,len=s.length(); i
四.字符串拼接
#include#include using namespace std;int main(){ string s1 = "first "; string s2 = "second "; char *s3 = "third "; char s4[] = "fourth "; char ch = '@'; string s5 = s1 + s2; string s6 = s1 + s3; string s7 = s1 + s4; string s8 = s1 + ch; cout< < < < < < < <
运行结果:
first secondfirst thirdfirst fourthfirst @五.insert() 插入字符串
#include#include using namespace std;int main(){ string s1, s2, s3; s1 = s2 = "1234567890"; s3 = "aaa"; s1.insert(5, s3); cout<< s1 <
运行结果
12345aaa67890
12345bbb67890六 erase() 删除string中的一个子字符串
#include#include using namespace std;int main(){ string s1, s2, s3; s1 = s2 = s3 = "1234567890"; s2.erase(5); s3.erase(5, 3); cout<< s1 <
运行结果:
1234567890
123451234590七 substr() 截取字符中的一个子字符串
#include#include using namespace std;int main(){ string s1 = "first second third"; string s2; s2 = s1.substr(6, 6); cout<< s1 <
运行结果:
first second third
second八 find() 查找某个字符串出现的位置
#include#include using namespace std;int main(){ string s1 = "first second third"; string s2 = "second"; int index = s1.find(s2,5); if(index < s1.length()) cout<<"Found at index : "<< index <
运行结果
Found at index : 6九.rfind() 从第二个参数开始往后查找
#include#include using namespace std;int main(){ string s1 = "first second third"; string s2 = "second"; int index = s1.rfind(s2,6); if(index < s1.length()) cout<<"Found at index : "<< index <
运行结果:
Found at index : 6
十 find_first_of() 查找子字符串首次出现的位置
#include#include using namespace std;int main(){ string s1 = "first second second third"; string s2 = "asecond"; int index = s1.find_first_of(s2); if(index < s1.length()) cout<<"Found at index : "<< index <
运行结果:
Found at index : 3