在C语言中,字符串被定义之后,大小不可改变,因此容易出现内存溢出的问题。C++的string部分的解决了这个问题,它会随存放字符的长度自动伸缩,程序员不必担心内存溢出的问题。string类还和c语言的字符串之间可以转换。
string类的声明
在C++语言中使用string类的话,需要包含头文件#include<string>
,这里不可以写成#include <string.h>
,后面这种写法是C中的写法。
string类位于std命名空间内,为了方便起见,可以在程序中添加using namespace std;
这条语句。这样,创建字符串语句就可以写成string str;
否则,创建字符串语句需要写成std::string str;
下面写个代码演示一下
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str; //创建对象
str="asdf"; //赋值
cout<<str; //输出
return 0;
}
string类的操作
赋值取值操作
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1("hello,world");
string str2(str1); //将str1的值拷贝给str2 该语句等价于string str2; str2.assign(str1);这两条语句
string str3(10,'c'); //str3为10个字符'c'
string str4(str1,5,4); //从下标为5(第一个下标为0)的字符算起,取4个字符
string str5("hello,world",5);//取前5个字符
cout<<str1<<endl;
cout<<str2<<endl;
cout<<str3<<endl;
cout<<str4<<endl;
cout<<str5<<endl;
return 0;
}
运行结果:
字符串的比较
在C语言中,比较字符串是比较麻烦的。在C++中使用的string类型可以快速比较字符串。
可以直接用运算符“>”,“<”,“>=”,“<=”直接比较字符串。
示例如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1("abcd");
string str2("abcd");
if(str1==str2)
cout<<"str1==str2";
else
cout<<"str1!=str2";
return 0;
}
运行结果:
string类的常用成员函数
1.string的交换
string str1("abc");
string str2("bcd");
str1.swap(str2);//str1与str2的值交换
2.string的查找
从左侧查找某字符第一次出现的位置的下标
string s("asdfghfgh");
string::size_type xiabiao;
xiabiao=s.find('d');
cout<<xiabiao;
//运行结果:2
从某个下标开始查找某字符
string s("asdfghfgh");
string::size_type xiabiao;
xiabiao=s.find("g",2);//从下标为2的字符往后找到g所在位置的下标
cout<<xiabiao;
//运行结果:4
从右侧查找
string s("asdfghfgh");
string::size_type xiabiao;
xiabiao=s.rfind("f");//从右侧查找该字符的第一个位置的下标
cout<<xiabiao;
//运行结果:6
.string的替换
替换指定字符
string s("I want to eat");
cout<<str1.replace(s.find('a'),2,"m");//从第一个字符开始查找,找到字符'a',从'a'开始往后两个字符被'm'替换
//运行结果:I wmt to eat
从头开始替换一段字符串
string s("I want to eat");
cout<<str1.replace(s.begin(),s.begin()+3,"*");//从第一个字符开始,往后3个字符被"*"替换
//运行结果:*ant to eat
string的插入
string str("1234567890");
cout<<str.insret(6,"asd");//6表示要插入位置的下标;asd表示要插入的字符串
//运行结果:123456asd7890
string的删除
string str("0123456789");
cout<<str.erase(5)<<endl;//从下标为5的位置开始,删除掉后面所有的字符
cout<<str.erase(6,3)<<endl;//从下标为6的字符开始,往后删除3个字符
//运行结果:01234
0123459
string的截取
string s("0123456789");
cout<<s.substr()<<endl;//截取全部字符
cout<<s.substr(6)<<endl;//从下标为6的字符开始,往后的全部被截取
cout<<s.substr(4,3)<<endl;//从下标为4的字符开始,往后截取3个字符
//运行结果:0123456789
6789
456
函数待补充~~~~~