使用string 类需要包含头文件:
#include<string>
初始化方法:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1("hello");
string month="March";
string s2(8,'x');
cout<<s1<<endl;//hello
cout<<month<<endl;//March
cout<<s2<<endl;//xxxxxxxx
string s;
s='n';//可以将字符值给string对象
cout<<s<<endl;//n
return 0;
}
string 的赋值
1)可以用 = 号赋值;
string s1("hello");
string s2;
s2=s1;
cout<<s2;//输出hello
2)用assign成员函数复制
string s1("hello");
string s2;
s2.assign(s1);
cout<<s2;//输出hello
//从s1中下标为0的字符开始复制3个字符
s2.assign(s1,0,3);
cout<<s2;//输出hel
return 0;
string类常用函数:
length().用来读取string对象的长度;
getline(cin,str);用来读取包含空格的字符串;
此外string还支持流读取运算符(遇空格停止)
string s1("hello");
cout<<s1<<' '<<s1.length()<<endl;//hello 5
getline(cin,s1);//输入hello girl
cout<<s1<<' '<<s1.length()<<endl;//输出为hello girl 10
cin>>s1;//输入hello girl
cout<<s1<<' '<<s1.length()<<endl;//输出仍为hello 5
另外compare函数可以用来比较string的大小
substr函数可用来取字符串的字串 swap函数可以用来交换两个字符串
string s1("hello");
string s2;
s2=s1.substr(2,4);
cout<<s2<<endl;//输出llo
s1.swap(s2);
cout<<s1<<" "<<s2<<endl;//输出llo hello
find()函数可用来从前往后查找字串第一次出现的位置并返回,如果找不到则返回string::npos
rfind()则是从后往前找。find()函数还可以指定开始查找的位置,find("str",i),i就是起始位置的下标。
另外还有find_first_of()和find_last_of()等函数大家有兴趣的可以了解一下。
string s1("hello");
cout<<s1.find("ll",1)<<endl;//输出2
erase()函数可以用来删除string中的字符
string s1("hello girl");
s1.erase(5);//删除下标5之后的字符
cout<<s1<<endl;//输出hello
replace()函数可以用来替换string中的字符
string s1("hello girl");
s1.replace(6,9,"world");//将下标从6到9的字符换成“world”
cout<<s1<<endl;//输出hello world
insert()函数可以在string中插入字符
string s1("hello girl");
string s2("world ");
s1.insert(6,s2);//将s2插入s1下标为6的位置,此处s2可以用任意字符串代替
cout<<s1<<endl;//输出hello world girl
c_str()函数可以转换成c语言式char*字符串
string s1("hello girl");
printf("%s\n",s1.c_str());//输出hello girl