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;

运行结果如下:

相关推荐
eqwaak03 分钟前
科技信息差(9.13)
大数据·开发语言·人工智能·华为·语言模型
郝学胜-神的一滴7 分钟前
深入探索 Python 元组:从基础到高级应用
运维·服务器·开发语言·python·程序人生
序属秋秋秋7 分钟前
《C++进阶之STL》【哈希表】
数据结构·c++·stl·哈希算法·散列表·哈希表·哈希
一只乔哇噻11 分钟前
java后端工程师进修ing(研一版‖day44)
java·开发语言·学习·算法
Ares-Wang30 分钟前
Vue3》》eslint Prettier husky
开发语言·javascript·ecmascript
EveryPossible1 小时前
静态箭头连线
开发语言·javascript·ecmascript
青草地溪水旁1 小时前
设计模式(C++)详解——建造者模式(1)
c++·设计模式·建造者模式
NiKo_W1 小时前
Git 版本回退与撤销修改
开发语言·git·安全
listhi5201 小时前
Map对象在JavaScript循环中的使用
开发语言·前端·javascript
大可门耳1 小时前
Qt第一课:Qt是什么?相对于其他框架的优劣势是什么
开发语言·qt