string字符串的常见库函数

string类
·string类是模板类:

typedef basic_string<char> string;

初始化有列表初始化,初始化的几种形式

//string的构造函数十分的多
	string s1("Hello");
	string mouth="March";
	string s2(8,'X');//连续输出8个X

注意字符初始化和数字初始化是不可以的

	string error1('U');
	string error2='C';
	string error3=22;
	string error4(8);

但是可以将字符赋值给string对象

	string s;
	s='n'

一些好用的成员函数

	length()//求字符串的长度

输入整行

	getline()//输入一行字符串当行末结束,空格是可以读入的

赋值

//成员函数的赋值
	//①:直接等号赋值
	//②:assign():功能很强,能够去部分赋值
	//全部赋值
	string s1("today"),s3;
	s3.assign(s1);
	//部分赋值
	string s1("comingtian"),s3;
	s3.assign(s1,13);//输出结果为omi

流读取

//支持流读取运算符,到空格,换行就会停下来
	string  stringObject;
	cin>>stringObject;

字符串中单个字符的访问

	//方式一:直接按照索引,类似与字符数组

	//成员函数:at(i)  去知名下标
	//at的成员函数会存在异常检查,如果产生异常就会抛出异常

字符串的连接:

	//+操作符对字符串进行连接

	//成员函数append():他会更强一点,他会指定从什么位置开始去进行连接
	

字符串的比较

//可以去进行字典序的比较

//符号:- == > >= < <= !=
//这些符号被重载了,使用上比较方便

//成员函数compare():可以整体比较和部分比较
//相等返回0,大于返回1,小于返回0.

取子串:十分的重要,太太太重要了。

//成员函数取子串
//下表从a开始到b
substr(a,b)

字符串当中去进行查找:
find家族:

find(“目标字符串”,起始为止,可以不写但是默认为0)
rfind(“目标字符串”,起始为止,可以不写但是默认为0)
如果发现能找到字符串,就会返回第一次出现该字符串出现的下标。
如果没有找到,就返回一个上述::npos

//成员函数:find():从前往后找
#include <iostream>
#include <string>
using namespace std;
int main(){
	string s1("helloworld and hello coming my home!");
	if(!s1.find("hello")) cout<<"the frist position is "<<s1.find("hello")<<endl;
	return 0;
//输出结果为:
//rfind():从后往前找,和前面是类似的
#include <iostream>
#include <string>
using namespace std;
int main(){
	string s1("helloworld and hello coming my home!");
	if(!s1.rfind("hello")) cout<<"the frist position is "<<s1.find("hello")<<endl;
	return 0;
}
//输出结果为:
#include <iostream>
#include <string>
using namespace std;
int main(){
	string s1("helloworld and hello coming my home!");
	cout<<"所在位置为 : "<<s1.find("hello",3);
	return 0;
}

删除操作:erase(),可以去设定删除起始位置

在这里插入代码片

猜你喜欢

转载自blog.csdn.net/weixin_44110100/article/details/106903958