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;

运行结果如下:

相关推荐
没有晚不了安3 分钟前
1.13作业
开发语言·python
布谷歌7 分钟前
Oops! 更改field的数据类型,影响到rabbitmq消费了...(有关于Java序列化)
java·开发语言·分布式·rabbitmq·java-rabbitmq
被程序耽误的胡先生12 分钟前
java中 kafka简单应用
java·开发语言·kafka
刀客12313 分钟前
python小项目编程-中级(1、图像处理)
开发语言·图像处理·python
卷卷的小趴菜学编程17 分钟前
c++之多态
c语言·开发语言·c++·面试·visual studio code
冷琴199637 分钟前
基于Python+Vue开发的反诈视频宣传管理系统源代码
开发语言·vue.js·python
楠枬1 小时前
网页五子棋——对战后端
java·开发语言·spring boot·websocket·spring
OopspoO1 小时前
C++ 标准库——函数对象和函数适配器
c++
kyle~1 小时前
thread---基本使用和常见错误
开发语言·c++·算法
攻城狮7号1 小时前
【第三节】C++设计模式(创建型模式)-单例模式
c++·单例模式·设计模式