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;

运行结果如下:

相关推荐
@大迁世界1 分钟前
用 popover=“hint“ 打造友好的 HTML 提示:一招让界面更“懂人”
开发语言·前端·javascript·css·html
星哥说事30 分钟前
Python自学12 — 函数和模块
开发语言·python
拾忆,想起42 分钟前
Redis复制延迟全解析:从毫秒到秒级的优化实战指南
java·开发语言·数据库·redis·后端·缓存·性能优化
点云侠1 小时前
解决Visual Studio 2022编译工程速度慢的问题
开发语言·c++·ide·算法·计算机视觉·visual studio
脚踏实地的大梦想家2 小时前
【Go】P2 Golang 常量与变量
开发语言·后端·golang
张璐月2 小时前
go docker-compose启动前后端分离项目 踩坑之旅
开发语言·docker·golang
禹曦a2 小时前
JavaScript性能优化实战指南
开发语言·javascript·性能优化
Swift社区2 小时前
Swift 解法详解:LeetCode 371《两整数之和》
开发语言·leetcode·swift
Swift社区2 小时前
Swift 解法详解 LeetCode 362:敲击计数器,让数据统计更高效
开发语言·leetcode·swift
ajassi20002 小时前
开源 C++ QT Widget 开发(十三)IPC通讯--本地套接字 (Local Socket)
linux·c++·qt·开源