C++(13)——string

上篇文章中介绍了中部分函数的用法,本篇文章将继续对其他的函数进行介绍:

1. substr:

cpp 复制代码
string substr (size_t pos = 0, size_t len = npos) const;

****函数的两个参数如上述代码所示,此函数的主要作用是根据一个已有的的对象的起始坐标开始,以长度为范围内的内容生成一个新的类型的对象。主要用于对一个已有的类型的对象进行分隔。例如:

cpp 复制代码
	string s1("hello world hello everyone");
	string s2 = s1.substr(0,5);
	string s3 = s1.substr(6, 5);
	string s4 = s1.substr(12, 5);
	string s5 = s1.substr(18, 8);

	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	cout << s5 << endl;

运行结果如下:

上面说到,常用于做一个已有类型的对象的内容分离,在进行分离时,常常会和一起进行使用。例如对于官网中对于函数的说明的网站链接如下:

cpp 复制代码
string s1("https://legacy.cplusplus.com/reference/string/string/substr/");
	size_t pos = s1.find(':');
	string s2, s3, s4, s5, s6;

		s2 = s1.substr(0, pos);
		cout << s2 << ' ' << endl;
		size_t pos1 = s1.find('/',pos+3);
		s3 = s1.substr(pos + 3, pos1 - pos - 3);
		cout << s3 << ' ' << endl;
		size_t pos2 = s1.find('/', pos1 + 1);
		s4 = s1.substr(pos1 + 1, pos2 - pos1 - 1);
		cout << s4 << ' ' << endl;
		s5 = s1.substr(pos2 + 1);
		cout << s5 << endl;

运行结果如下:

2. find_first_of:

cpp 复制代码
size_t find_first_of (const string& str, size_t pos = 0) const;

size_t find_first_of (const char* s, size_t pos = 0) const;

size_t find_first_of (const char* s, size_t pos, size_t n) const;

对于find_first_of函数,其大体意义如下:给定一个类型的对象或者字符串或者字符,在不给定参数的情况下,在给定的上述三个类型中,从另一个类型的对象中寻找上述三个类型的内容,并且返回他们的坐标,下面将给出其中几个函数的使用方法:

2.1 size_t find_first_of (const string& str, size_t pos = 0) const:

例如:给定一个字符串,同时存在一个类型的对象,其内容为:

如果需要将上述对象中所有在字符串中出现的字母,即替换为:

cpp 复制代码
string str("Please, replace the vowels in this sentence by asterisks.");
	size_t pos = str.find_first_of("aeiou");
	while (pos != str.npos)
	{
		str[pos] = '*';
		pos = str.find_first_of("aeiou");

	}
	cout << str << '\n';

对于上述代码,起运行结果为:

2.2 size_t find_first_of (const char* s, size_t pos = 0) const:

此函数的使用方法与上一小节中的方法相同,只是参数的类型发生了改变,故不再赘述。

2.3 size_t find_first_of (const char* s, size_t pos, size_t n) const:

依旧是使用小节中的例子:

假如只需要将给定字符串的前两个字母在类型的对象出现时替换为

cpp 复制代码
string str("Please, replace the vowels in this sentence by asterisks.");
	size_t pos = str.find_first_of("aeiou",0,2);
	while (pos != str.npos)
	{
		str[pos] = '*';
		pos = str.find_first_of("aeiou",0,2);

	}
	cout << str << '\n';
	return 0;

运行结果如下:

相关推荐
CodeWithMe34 分钟前
【C/C++】namespace + macro混用场景
c语言·开发语言·c++
蓝婷儿42 分钟前
6个月Python学习计划 Day 17 - 继承、多态与魔术方法
开发语言·python·学习
Mikhail_G1 小时前
Python应用变量与数据类型
大数据·运维·开发语言·python·数据分析
YuTaoShao1 小时前
Java八股文——集合「List篇」
java·开发语言·list
SuperCandyXu1 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
Bl_a_ck2 小时前
【JS进阶】ES6 实现继承的方式
开发语言·前端·javascript
愈努力俞幸运2 小时前
c++ 头文件
开发语言·c++
永日456702 小时前
学习日记-day24-6.8
开发语言·学习·php
BillKu2 小时前
Java后端检查空条件查询
java·开发语言
~山有木兮2 小时前
C++设计模式 - 单例模式
c++·单例模式·设计模式