C/C++学习笔记-string(增删改查)

查:

功能:在字符串中查找某个字符或字符串。

函数:find(str,pos),rfind(str,pos),find_first_of(str,pos),find_last_of(str,pos)。

         参数:str,要查找的字符或字符串;pos,查找的起始位置。

std::string str = "abc123abc456";

/*  str=| a | b | c | 1 | 2 | 3 | a | b | c | 4 | 5  | 6  |
 *  inx=| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |*/

std::cout << str.find("a",0)<< std::endl;//0,find()返回的是从0位置起,第一次出现的位置
std::cout << str.find("a",1)<< std::endl;//6,
std::cout << str.find("abc")<< std::endl;//0,位置不填写的话,默认是从0开始。

std::cout << str.rfind("a",8)<< std::endl;//6,rfind()返回的是从8位置起,向前查找第一次出现
std::cout << str.rfind("a",2)<< std::endl;//0
std::cout << str.rfind("abc")<< std::endl;//6,位置不填写的话,默认是从最后位置向前查找开始。6

总结:位置标号是从0开始的;rfind是逆向开始查找的;

find_first_of,find_last_of的应用环境,我们需要在str中,找到'a','h','5'中任何一个最先出现的并返回下标。那么利用find的做法是先查找a,如果找到则返回一个下标,再查找h.....,最后比较所有下标,选出最小的一个。是不是很麻烦?现在只需一个函数。

	std::string str1 = "ah5";

	std::cout << str.find_first_of(str1,0)<< std::endl;//0
	std::cout << str.find_last_of(str1,30)<< std::endl;//10

find_first_of:为顺序查找,在str中,a和5均出现了,但是a最先出现,所以返回0;

find_last_of:为逆序查找,在str中,反向看的话5最先出现,所以返回10

扩展:

需求:要求返回str中包含a,h,5的所有位置下标。分析:因为find等所有函数返回的是第一次出现的小标,因此,当我们第一次得到下标时,接着在以该位置为起点继续find。

	int i = str.find_first_of(str1,0);

	while(i != -1){
		std::cout<<i<<" ";
		i = str.find_first_of(str1,i+1);
	}

删:

功能:删除字符串中某个字符或字符串

函数:erase(int pos,int n)/erase(iterator start,iterator end)

参数:重载函数有两个,即是说有两套参数。第一套:int pos为删除字符下标,int n表示在pos开始连续删除n个字符。例如:

str.erase(4,2):从下标为2的字符开始,连续删除2个字符。第二套参数:注意为迭代器。一般str.begin();str.end()都是返回的迭代器。

第一套参数的使用(删除位置4,即‘2’开始的两个字符,即‘2’和‘3’)

	std::string str = "abc123abc456";
	/*  str=| a | b | c | 1 | 2 | 3 | a | b | c | 4 | 5  | 6  |
	 *  inx=| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |*/
	str.erase(4,2);//abc1abc456

第二套参数(传参为迭代器)(推荐):

	std::string str = "abc123abc456";
	/*  str=| a | b | c | 1 | 2 | 3 | a | b | c | 4 | 5  | 6  |
	 *  inx=| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |*/
	str.erase(str.begin()+4,str.begin()+6);//abc1abc456
        //str.erase(str.begin()+4);//abc13abc456
	std::cout<<str<<std::endl;

实现与上面的同样功能。注意为什么要用begin,因为begin返回的是迭代器,而我们的入参必须是迭代器。功能,删除4到6这段的字符(不包括6),当然还可以删除某个位置上的字符,就只需传入一个参数就可以了。

增:

功能:在str中特定位置插入字符或字符串

函数:insert()

该函数有多个重载,只需要在erase函数中,搞明白迭代器,就很容易懂。

 string &insert(int p0, const char *s);——在p0位置插入字符串s

string &insert(int p0, const char *s, int n);——在p0位置插入字符串s的前n个字符

string &insert(int p0,const string &s);——在p0位置插入字符串s

string &insert(int p0,const string &s, int pos, int n);——在p0位置插入字符串s从pos开始的连续n个字符

string &insert(int p0, int n, char c);//在p0处插入n个字符c

iterator insert(iterator it, char c);//在it处插入字符c,返回插入后迭代器的位置

void insert(iterator it, const_iterator first, const_iteratorlast);//在it处插入从first开始至last-1的所有字符

void insert(iterator it, int n, char c);//在it处插入n个字符c

改:

功能:替换str中的某处或多处

函数:repalce()

猜你喜欢

转载自blog.csdn.net/qq_35703954/article/details/81665127