C++入门篇7---string类

news2025/2/11 15:48:24

所谓的string类,其实就是我们所说的字符串,本质和c语言中的字符串数组一样,但是为了更符合C++面向对象的特性,特地将它写成了一个单独的类,方便我们的使用

对其定义有兴趣的可以去看string类的文档介绍,这里就不做过多的介绍了

一、了解string类的接口,及其相关的功能

1.构造函数相关接口

(constructor)函数名称功能说明
string()构造空的string对象,即空字符串
string(const char*s)用C中的字符串构造string类
string(size_t n,char c)用n个c字符创建string对象
string(const string& s)

 拷贝构造  

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s1;
	string s2("hhh");
	string s3(3,'a');
	string s4(s2);
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	return 0;
}

 2. string类对象的容量操作

函数名称功能说明
size返回字符串的有效长度,'\0'除外
length返回字符串的有效长度,和上面一个函数功能一样
capacity返回空间大小(即共能存放多少个字符,'\0'除外)
empty检查字符串是否为空
clear清空字符串,但一般不释放空间,即capacity不变
reserve为字符串预留空间,减少扩容次数
resize将有效字符的个数改成n个,多出来的空间用字符c(传入参数)填充
shrink_to_fit将字符串的capacity缩小至和size一样大,(一般不用)
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s("hello world");
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s.empty() << endl;
	cout << "------------" << endl;

	s.clear();
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s.empty() << endl;
	cout << "------------" << endl;

	s.reserve(100);
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s.empty() << endl;
	cout << "------------" << endl;

	s.resize(10, 'a');
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s.empty() << endl;
	cout << "------------" << endl;

	return 0;
}

注意:1. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。

2.reserve(size_t n = 0)为string预留空间,不改变有效元素个数,当reserve的参数小于
string的底层空间总大小时,reserver不会改变容量大小。

3.string类对象的访问及遍历操作

函数名称功能说明
operator[ ]返回pos位置的字符
begin+endbegin获取第一个字符的迭代器+end获取最后一个字符下一个位置的迭代器
rbegin+rendrbegin获取最后一个字符的迭代器+rend获取第一个字符前一个位置的迭代器
范围forC++11支持更简洁的范围for的新遍历方式
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string x = "hello world";
	//本质是隐式类型转化+拷贝构造,即调用构造函数创建临时变量,然后拷贝构造,编辑器优化后是一个构造函数
	string::iterator it1 = x.begin();//正向迭代器
	//这里不建议用it1<x.end(),因为string类的迭代器it1++底层是指针后移,
	//但是其他类的迭代器不一定是这样实现的,而!=是通用的
	while (it1 != x.end())
	{
		cout << *it1 << " ";
		++it1;
	}
	cout << endl;

	string::reverse_iterator it2 = x.rbegin();//逆向迭代器
	while (it2 != x.rend())
	{
		cout << *it2 << " ";
		++it2;
	}
	cout << endl;


	for (auto& s : x)//底层实现就是上面的正向迭代器
	{
		cout << s << " ";
	}
    cout << endl;

	for (int i = 0; i < x.size(); i++)
	{
		cout << x[i] << " ";
	}
	const string y = "good game";
	string::const_iterator it3 = y.begin();//具有常属性的对象的迭代器写法
	string::const_reverse_iterator it4 = y.rbegin();
	return 0;
}

 

 4.string类对象的修改操作

函数名称功能说明
push_back在字符串后尾插字符c
append在字符后追加一个字符串
operator+=在字符串后追加字符串/字符
c_str返回C语言格式的字符串
find从字符串pos位置开始往后找字符c,返回该字符在字符串中的下标
rfind从字符串pos位置开始往前找字符c,返回该字符在字符串中的下标
substr在str中从pos位置开始,截取n哥字符,然后将其返回

 下面是一些测试用例,可以去自己调试调试,当然还有写其他的用法没写,有兴趣可以去查查文档,一般来说下面的用法就够用了

void test1()
{
	string x;
	x.push_back('a');
	x.push_back('b');
	x.push_back('c');
	cout << x << endl;
	x.append("def");
	cout << x << endl;
	x += 'e';
	cout << x << endl;
	x += "fgh";
	cout << x << endl;
}

void test2()
{
	string x = "test.txt";
	FILE* fp = fopen(x.c_str(), "w");
	//...
	//当我们调用C语言中的一些需要类似char*参数的相关接口时,
	//我们就需要将string转成C语言中的字符串,进行调用
	fclose(fp);
}

void test3()
{
	string s = "hello world";
	size_t p = s.find('l');//默认从起始位置开始找
	if (p != string::npos)//没找到时会返回npos
		cout << p << " " << s[p] << endl;

	p = s.find('l',5);//从下标为5的位置开始找
	if (p != string::npos)
		cout << p << " " << s[p] << endl;

	p = s.find("world");//默认从其实位置开始找
	if (p != string::npos)
		cout << p << " " << s[p] << endl;

	p=s.find("world",3);//从下标为3的位置开始找
	if (p != string::npos)
		cout << p << " " << s[p] << endl;

	p = s.find("word", 1, 2);//从下标1开始找和word前两个字符匹配的地方
	if (p != string::npos)
		cout << p << " " << s[p] << endl;

	//string x = "word";
	//p = s.find(x, 1);//从下标1开始在s中找x,也可以默认从0开始
	//rfind用法和find用法一样
}

void test4()
{
	string x = "you are right";
	cout << x.substr(0, 3) << endl;//从下标0开始往后取3个字符返回,返回类型是string
	cout << x.substr(4, 3) << endl;//从下标4开始往后取3个字符返回,返回类型是string
	cout << x.substr(8, 5) << endl;//从下标8开始往后取5个字符返回,返回类型是string
}

int main()
{
	//test1();
	//test3();
	//test4();
	return 0;
}

5.string类的非成员函数介绍

函数名称功能说明
operator++运算符重载
operator>>输入运算符重载
operator<<输出运算符重载
getline获取一行字符串

上面的函数就不一一枚举用法了,基本一看就懂,不确定的可以去查查文档,或者自己调试看看

总结:string相关的接口一般就是这些,还有些不常用没写,如果感兴趣可以去查查文档,学完后可以去找些题目来练练,其实很快就能记住string的常用接口用法

二、实现string类的常用接口

#include<iostream>
using namespace std;
#include<assert.h>
namespace zxws
{
	class string
	{
	public:
		string(const char* str = "")
			:_size(strlen(str))
			, _capacity(strlen(str))
		{
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}

		void swap(string& tmp)
		{
			std::swap(_str, tmp._str);
			std::swap(_size, tmp._size);
			std::swap(_capacity, tmp._capacity);
		}

		string(const string& s)
			:_str(nullptr)
			,_size(0)
			,_capacity(0)
		{
			string tmp(s._str);
			swap(tmp);
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}

		const char* c_str() const
		{
			return _str;
		}
		string& operator=(string tmp)
		{
			swap(tmp);
			return *this;
		}

		char& operator[](size_t pos)
		{
			assert(pos < _size);
			return _str[pos];
		}

		const char& operator[](size_t pos) const
		{
			assert(pos < _size);
			return _str[pos];
		}

		size_t size() const
		{
			return _size;
		}

		size_t capacity()const
		{
			return _capacity;
		}

		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;
				_capacity = n;
			}
		}

		void resize(size_t n,char x = '\0')
		{
			if (n <= _size)
			{
				_str[n] = '\0';
				_size = n;
			}
			else
			{
				reserve(n);
				while (n--)
				{
					push_back(x);
				}
			}
		}

		void push_back(char x)
		{
			if (_size == _capacity)
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			_str[_size++] = x;
			_str[_size] = '\0';
		}

		void append(const char* str)
		{
			size_t len = strlen(str);
			if (_size + len > _capacity)
				reserve(_size + len);
			strcpy(_str+_size, str);
			_size += len;
		}

		void append(size_t n, char x)
		{
			reserve(_size + n);
			while (n--)
			{
				push_back(x);
			}
		}

		string& operator+=(char x)
		{
			push_back(x);
			return *this;
		}

		string& operator+=(const char* str)
		{
			append(str);
			return *this;
		}

		size_t find(char x, size_t pos = 0)
		{
			assert(pos < _size);
			for (size_t i = pos; i < _size; i++)
			{
				if (x == _str[pos])
					return i;
			}
			return npos;
		}

		size_t find(const char* str, size_t pos = 0)
		{
			assert(pos < _size);
			char* p = strstr(_str, str);
			return p == nullptr ? npos : p - _str;
		}

		void insert(size_t pos, char x)
		{
			assert(pos <= _size);
			reserve(_size + 1);
			for (size_t i = _size + 1; i > pos; i--)
			{
				_str[i] = _str[i - 1];
			}
			_str[pos] = x;
			_size++;
		}

		void insert(size_t pos, const char* str)
		{
			assert(pos < _size);
			size_t len = strlen(str);
			reserve(_size + len);
			for (size_t i =_size+1,j=_size+len ; i > pos; i--,j--)
			{
				_str[j] = _str[i - 1];
			}
			strncpy(_str + pos, str, len);
			_size += len;
		}

		void erase(size_t pos,size_t n=npos)
		{
			assert(pos < _size);
			if (n == npos || pos + n >= _size)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				for (size_t i = pos, j = pos + n; j <= _size; i++, j++)
				{
					_str[i] = _str[j];
				}
				_size -= n;
			}
		}

		typedef char* iterator;
		typedef const char* const_iterator;

		iterator begin()
		{
			return _str;
		}
		
		const_iterator begin() const
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		const_iterator end() const
		{
			return _str + _size;
		}

		string substr(size_t pos,size_t n=npos) const
		{
			assert(pos < _size);
			string tmp;
			size_t end = pos + n;
			if (n == npos || pos + n >= _size)
			{
				n = _size - pos;
				end = _size;
			}
			tmp.reserve(n);
			for (size_t i = pos; i < end; i++)
				tmp += _str[i];
			return tmp;
		}

		bool operator<(const string& s) const
		{
			return strcmp(_str, s._str) < 0;
		}

		bool operator==(const string& s) const
		{
			return strcmp(_str, s._str) == 0;
		}

		bool operator<=(const string& s) const
		{
			return *this<s||*this==s;
		}

		bool operator>(const string& s) const
		{
			return !(*this <= s);
		}

		bool operator>=(const string& s) const
		{
			return !(*this < s);
		}

		bool operator!=(const string& s) const
		{
			return !(*this == s);
		}

		void clear()
		{
			_str[0] = '\0';
			_size = 0;
		}

	private:
		char* _str;
		size_t _size;
		size_t _capacity;
		const static size_t npos;

		friend ostream& operator<<(ostream& cout, const string& s);
		friend istream& operator>>(istream& cin, const string& s);
	};
	const size_t string::npos = -1;

	ostream& operator<<(ostream& cout, const string& s)
	{
		for (size_t i = 0; i < s._size; i++)
		{
			cout << s[i];
		}
		return cout;
	}

	istream& operator>>(istream& cin, string& s)
	{
		s.clear();
		char buff[129] = { 0 };
		char x = getchar();
		int i = 0;
		while (x == ' ' || x == '\n')
			x = getchar();
		while (x != '\n' && x != ' ')
		{
			buff[i++] = x;
			if (i == 128)
			{
				buff[i] = '\0';
				s += buff;
				i = 0;
			}
			x = getchar();
		}
		if (i) {
			buff[i] = '\0';
			s += buff;
		}
		return cin;
	}
};

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/864441.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【在树莓派上安装cpolar内网穿透实战】

文章目录 前言1.在树莓派上安装cpolar2.查询cpolar版本号3.激活本地cpolar客户端4.cpolar记入配置文件 前言 树莓派作为一个超小型的电脑系统&#xff0c;虽然因其自身性能所限&#xff0c;无法如台式机或笔记本等准系统一样&#xff0c;运行大型软件或程序&#xff08;指望用…

ecology-自定义浏览按钮实现多处引用可定制不同查询条件。

1.新建ecode代码&#xff0c;前置加载&#xff0c;代码内容&#xff1a; ecodeSDK.overwritePropsFnQueueMapSet(WeaBrowser,{ //组件名fn:(newProps)>{ //newProps代表组件参数 if(newProps.type162 || newProps.type161){//console.log("自定义浏览框");if(!ne…

日常BUG——使用Long类型作id,后端返回给前段后精度丢失问题

&#x1f61c;作 者&#xff1a;是江迪呀✒️本文关键词&#xff1a;日常BUG、BUG、问题分析☀️每日 一言 &#xff1a;存在错误说明你在进步&#xff01; 一、问题描述 数据库long类型Id: 前端返回的Id实体类: Data ApiModel("xxx") public class …

数据结构顺序表

今天主要讲解顺序表&#xff0c;实现顺序表的尾插&#xff0c;头插&#xff0c;头删&#xff0c;还有尾删等操作&#xff0c;和我们之前写的通讯录的增删查改有类似的功能。接下来让我们开始我们的学习吧。 1.线性表 线性表&#xff08;linear list&#xff09;是n个具有相同特…

保证接口数据安全的10种方式

我们日常开发中&#xff0c;如何保证接口数据的安全性呢&#xff1f;个人觉得&#xff0c;接口数据安全的保证过程&#xff0c;主要体现在这几个方面&#xff1a;一个就是数据传输过程中的安全&#xff0c;还有就是数据到达服务端&#xff0c;如何识别数据&#xff0c;最后一点…

安达发|企业如何提高生产实现精细化管理

随着市场竞争的加剧&#xff0c;企业如何提高生产效率和降低成本成为了关键。本文将探讨生产计划排程表的制定方法&#xff0c;帮助企业实现精细化管理&#xff0c;提升竞争力。 在传统的生产管理中&#xff0c;企业往往依赖于人工经验和直觉来制定生产计划&#xff0c;导致生产…

docker复现Nginx配置漏洞

目录 1.docker环境搭建 2.复现过程 2.1CRLF(carriage return/line feed)注入漏洞 2.2.目录穿越 2.3.add_header覆盖 1.docker环境搭建 1.安装docker apt-get update apt-get install docker.ioyum install docker.io 2.下载并解压docker环境Nginx配置漏洞安装包 链接&am…

最强的表格组件—AG Grid使用以及License Key Crack

PS: 想要官方 License Key翻到最后面 Ag Grid简介 Ag-Grid 是一个高级数据网格&#xff0c;适用于JavaScript/TypeScript应用程序&#xff0c;可以使用React、Angular和Vue等流行框架进行集成。它是一种功能强大、灵活且具有高度可定制性的表格解决方案&#xff0c;提供了丰富…

23款奔驰AMG GT50升级原厂HUD抬头显示系统,增加您的行车安全性

HUD是平视显示器的简称&#xff0c;它原先是运用在航空器上的飞行辅助仪器。指飞行员不需要低头&#xff0c;就能够看到他需要的重要资讯。由于HUD的方便性以及能够提高飞行安全&#xff0c;这项技术后来也发展到汽车行业。汽车搭载的HUD抬头数字显示功能&#xff0c;是利用光学…

类的默认成员函数(C++)

类的默认成员函数 1.构造函数特性 2.析构函数特性 3.拷贝构造函数特性 4.赋值重载函数运算符重载赋值运算符重载 const成员函数取地址运算符重载 1.构造函数 构造函数是一个特殊的成员函数&#xff0c;名字与类名相同&#xff0c;创建类类型对象时由编译器自动调用&#xff0c…

怎么制作gif动态图?gif图片在线制作攻略分享

现在许多品牌和营销活动也使用gif动态图来吸引用户注意力、提升品牌形象或传递特定的信息&#xff0c;那么gif制作的过程到底难不难呢&#xff1f;其实只需要使用gif图片在线制作工具就非常简单了&#xff0c;下面以图片制作gif&#xff08;https://www.gif.cn&#xff09;为例…

一个事务插入,另外一个事务更新操作,是否会更新成功?

1.前言 同样另外一个非常有意思的题目&#xff0c;值得我们思考。大概背景是这个样子的。如果有一个事务A进行插入 id > 100, 同时另外一个事务B进行更新update id > 100。那么事务B是否会更新成功。我们来画一个时序图&#xff1a; time事务A事务B备注T1insert id >…

MPAS-A原理及陆面模式的基本概念

跨尺度预测模式&#xff08;The Model for Prediction Across Scales - MPAS&#xff09;是由洛斯阿拉莫斯实验室和美国国家大气研究中心(NCAR)共同开发&#xff0c;其由3个部分组成&#xff0c;分别称为 MPAS-A&#xff08;大气模型&#xff09;、MPAS-O&#xff08;海洋模型&…

Nginx+Tomcat负载均衡、动静分离实例详细部署

一、反向代理两种模式 四层反向代理 基于四层的iptcp/upd端口的代理 他是http块同一级&#xff0c;一般配置在http块上面。 他是需要用到stream模块的&#xff0c;一般四层里面没有自带&#xff0c;需要编译安装一下。并在stream模块里面添加upstream 服务器名称&#xff0c;…

uni-app日期选择器

写个简单的日期选择器&#xff0c;还没搞样式&#xff0c;所以有点丑 大概长这样吧 首先是这个picker选择器&#xff0c;mode选择日期&#xff0c;end是写一个范围前日期&#xff0c;:end就是这个日期是动态变化的&#xff0c;还有change函数 <template><view>&l…

LeetCode150道面试经典题--验证回文串(简单)

1.题目 如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后&#xff0c;短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。 字母和数字都属于字母数字字符。 给你一个字符串 s&#xff0c;如果它是 回文串 &#xff0c;返回 true &#xff1b;否…

通过这些case,我把项目LCP时间减少了1.5s

您好&#xff0c;如果喜欢我的文章&#xff0c;可以关注我的公众号「量子前端」&#xff0c;将不定期关注推送前端好文~ 前言 最近在做公司几个项目性能优化&#xff0c;整理出一些比较有用且常见的case来分享一下。 A项目优化 白屏相关 DNS预连接、资源预解析 对于公共域…

还不会python 实现常用的数据编码和对称加密?看这篇文章就够啦~

♥ 前 言 相信很多使用 python 的小伙伴在工作中都遇到过&#xff0c;对数据进行相关编码或加密的需求&#xff0c;今天这篇文章主要给大家介绍对于一些常用的数据编码和数据加密的方式&#xff0c;如何使用 python 去实现。话不多说&#xff0c;接下来直接进入主题&#xf…

install imap error

【错误翻译】 Try to run this command from the system terminal. Make sure that you use the correct version of pip installed for your Python interpreter located at D:\Program Files (x86)\Python\Python39\python.exe. 尝试从系统终端运行此命令。请确保使用安装在…