C++系列-String(一)

🌈个人主页:羽晨同学

💫个人格言:"成为自己未来的主人~"

string是用于字符串,可以增删改查

首先,我们来看一下string的底层

接下来,我们来看一下string的常用接口有哪些:

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<list>
#include<algorithm>
using namespace std;

void test_string1()
{
	//常用
	string s1;
	string s2("hello world");
	string s3(s2);
	cout << s3;
}
int main()
{
	test_string1();

	return 0;
}

我们可以看到的是,string起到了拷贝字符串的作用。

接下来是一些不常用的接口功能:

cpp 复制代码
	string s4(s3, 3, 5);
	cout << s4 << endl;

我们可以看到这个接口的功能是从下标为3开始,向后拷贝五个字节

cpp 复制代码
	string s5(s2, 3);
	cout << s5 << endl;

我们可以看到,这个接口的目的是从下标为3开始,一直拷贝到结尾

cpp 复制代码
	string s6(s2, 3, 30);
	string s7("hello world", 5);
	string s8(10, 'x');
	cout << s6 << endl;
	cout << s7 << endl;
	cout << s8 << endl;

在接下来的接口6,7,8,这三个接口当中,想要实现的功能分别为

接口6是下标为3开始到30,由于30大于最大长度,所以到字符串的结尾

接口7是拷贝前5个

接口8是拷贝10个x

接下来,让我们看一下下面的这段代码:

cpp 复制代码
void test_string2()
{
	//隐式类型转换
	string s2 = "hello world";
	string& s3 = "hello world";
}

在这段代码中,涉及到的知识点为隐式类型转换,我们都知道,临时变量具有常性,所以这段代码会出现报错,报错原因是由于权限的放大。

所以,我们需要再前面加上一个const

cpp 复制代码
void test_string2()
{
	//隐式类型转换
	string s2 = "hello world";
	const string& s3 = "hello world";
}

这样子,我们就避免了权限放大的这个问题。

cpp 复制代码
void push_back(const string &s)
{

}

void test_string2()
{
	//隐式类型转换
	string s2 = "hello world";
	const string& s3 = "hello world";
	//构造
	string s1("hello world");
	push_back(s1);
	push_back("hello world");
}

在这段代码中我们可以看到,当传参的时候,我们既可以传临时变量,也可以传字符串

接下来让我们简单实现一下string中的operator\[\]的粗略逻辑:

cpp 复制代码
class string
{
public:
	//引用返回
	//1.减少拷贝
	//2.修改返回对象
	char& operator[](size_t i)
	{
		assert(i < _size);
		return _str[i];
	}
private:
	char* _str;
	size_t _size;
	size_t _capacity;

};

这个告诉我们一件什么事情呢?那就是在\[\]中是存在暴力检查的。

相关推荐
阿里嘎多学长13 分钟前
2026-09-20 GitHub 热点项目精选
开发语言·程序员·github·代码托管
2401_8390805428 分钟前
C++常见八股
数据结构·c++·算法
qq_199886871 小时前
第6板块 第2节 CUDA运行时API与驱动API 核心笔记
c++·人工智能·gpu算力
syagain_zsx2 小时前
算法基础篇 · 03 枚举(C++ 题解)
c++·算法·二进制·枚举
weixin_307779132 小时前
C++代码实现MATLAB中的ode23tb函数功能
开发语言·c++·算法·matlab
2601_966949652 小时前
为什么量化回测中 for 循环比 DataFrame 慢三个数量级?从向量化原理讲起
开发语言·python·pandas·股票数据·quantdash
S_WEAN3 小时前
C++STL - string类的模拟实现
c++
S_WEAN3 小时前
【C++】STL - string类
c++
码匠许师傅3 小时前
【C++三方组件】toml++:人性化的配置文件格式
c++