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;

运行结果如下:

相关推荐
嘉琪0017 分钟前
2025 js——面试题(7)——ajax相关
开发语言·javascript·ajax
SoniaChen339 分钟前
Rust基础-part3-函数
开发语言·后端·rust
一个天蝎座 白勺 程序猿12 分钟前
飞算JavaAI进阶:重塑Java开发范式的AI革命
java·开发语言·人工智能
liu_yueyang13 分钟前
JavaScript VMP (Virtual Machine Protection) 分析与调试
开发语言·javascript·ecmascript
前端 贾公子15 分钟前
tailwindCSS === 使用插件自动类名排序
java·开发语言
10岁的博客15 分钟前
代码编程:一场思维与创造力的革命
开发语言·算法
七七七七0715 分钟前
C++类对象多态基础语法【超详细】
开发语言·c++
C嘎嘎嵌入式开发42 分钟前
python之set详谈
开发语言·python
定偶42 分钟前
进制转换小题
c语言·开发语言·数据结构·算法
真的想上岸啊1 小时前
学习C++、QT---21(QT中QFile库的QFile读取文件、写入文件的讲解)
c++·qt·学习