string类学习

news2024/9/20 14:46:14

本篇将深入学习string类,通过各个测试函数玩遍c++string类,学到就是赚到!!!

文章目录

  • 1.头文件和源文件
    • 1.1源文件
    • 1.2头文件
  • 2.构造函数
  • 3.赋值重载函数
  • 4.元素访问运算符
  • 5.迭代器
    • 5.1正向迭代器
    • 5.2反向迭代器
  • 6.添加字符串
  • 7.vs下扩容机制
  • 8.insert()函数
  • 9.c_str()函数
  • 10.find、rfind、substr
    • 10.1综合应用
    • 10.2rfind()应用
  • 11.find_first_of
  • 12.字符串转换
  • 13.运行结果

1.头文件和源文件

完整代码点击 string类学习 跳转码云获取

1.1源文件

#include"string.h"
int main()
{
	/*test_string01();
	test_string02();
	test_string03();
	test_string04();
	test_string06();
	test_string07();
	test_string08();
	test_string09();
	test_string10();
	test_string11();
	test_string12();
	test_string13();*/
	return 0;
}

1.2头文件

#paragma once
#include<iostream>
#include<string>
#include<list>
#include<assert.h>
using namespace std;

2.构造函数

void test_string01()
{
	//1.无参构造 string();
	string s1;
	
	//2.有参构造 string (const char* s);
	//string s2("hello world"); 
	string s2 = "hello world";//*s--tmp--s2  构造+拷贝
	
	//3.拷贝构造 string (const string& str);
	string s3(s2);
	
	//4.部分拷贝构造
	//string(const string & str, size_t pos, size_t len = npos);
	//len参数分析:
	//(1)不传参:取缺省值-1==取到结尾
	//(2)len > n:取到结尾
	string s4(s2, 6, 5);
	
	//5.部分构造string (const char* s, size_t n);
	string s5("hello world", 5);
	
	//6.字符构造string (size_t n, char c);
	string s6(10, '*');
}

3.赋值重载函数

void test_string02()
{
	string s1;
	string s2 = "hello world";//构造+拷贝->构造

	//1.string& operator= (const string& str);
	s1 = s2;

	//2.string& operator= (const char* s);
	s1 = "xxx";

	//3.string& operator= (char c);
	s1 = 'x';
}

4.元素访问运算符

void test_string03()
{
	string s1("hello world");
	//s1.operator[](2)
	cout << s1[2] << endl;
	s1[2] = 'x';
	cout << s1[2] << endl;
	//1.char& operator[] (size_t pos); 
	//遍历string,每个字符+1
	for (size_t i = 0; i < s1.size(); i++)
	{
		s1[i]++;
	}
	cout << s1 << endl;

	//2.const char& operator[] (size_t pos) const;
	const string s2("world");
	for (size_t i = 0; i < s1.size(); i++)
	{
		cout << s2 << endl;
	}

	//3.内部检查越界
	//s2[6];

	//at运算符
	//与operator[]区别:
	// 越界抛异常
	//char& at(size_t pos); 
	//const char& at(size_t pos) const;
}

5.迭代器

5.1正向迭代器

在这里插入图片描述

//iterator begin();
//const_iterator begin() const;
void test_string04()
{
	//1.遍历s
	string s("hello");
	string::iterator it = s.begin();
	while (it != s.end())
	{
		(*it)++;
		cout << *it << " ";
		++it;
	}
	cout << endl;

	// 2.范围for -- 自动迭代,自动判断结束
	// 依次取s中每个字符,赋值给ch

	/*for (auto ch : s)
	{
		ch++;
		cout << ch << " ";
	}*/

	for (auto& ch : s)
	{
		ch++;
		cout << ch << " ";
	}
	cout << endl << s << endl;

	//3.list同样适用
	list<int> lt(10, 1);
	list<int>::iterator lit = lt.begin();
	while (lit != lt.end())
	{
		cout << *lit << " ";
		++lit;
	}
	cout << endl;

	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;

	// 范围for底层其实就是迭代器
}

5.2反向迭代器

在这里插入图片描述

void func(const string& str)
{

	//正向迭代器
	//string::const_iterator it = str.begin();
	auto it = str.begin();
	while (it != str.end())
	{
		//*it = 'x';
		cout << *it << " ";
		++it;
	}
	cout << endl;

	//反向迭代器
	//string::const_reverse_iterator rit = str.rbegin();
	auto rit = str.rbegin();
	while (rit != str.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
}

void test_string05()
{
	string s("hello");
	string::reverse_iterator rit = s.rbegin();
	while (rit != s.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;

	func(s);
	//迭代器:
	// 
	//iterator begin();
	//const_iterator begin() const;

	//reverse_iterator rbegin(); 
	//const_reverse_iterator rbegin() const;
}

6.添加字符串

void test_string06()
{
	//void push_back(char c);
	string s("hello");
	s.push_back('-');
	s.push_back('-');
	//string& append(const char* s);
	s.append("world");
	cout << s << endl;

	//string& operator+= (const string & str);
	//string & operator+= (const char* s);
	//string& operator+= (char c);
	string str("我来了");
	s += str;
	s += "!!!";
	s += '@';
	cout << s << endl;

	//template <class InputIterator>   
	//string& append(InputIterator first, InputIterator last);
	s.append(++str.begin(), --str.end());
	cout << s << endl;

	//string copy(++s.begin(), --s.end());
	string copy(s.begin() + 5, s.end() - 5);
	cout << copy << endl;
}

7.vs下扩容机制

void test_string07()
{
	//string s1("11111111111111");
	//cout << s1.max_size() << endl;
	//cout << s1.capacity() << endl;

	string s;
	s.reserve(1000);       //开空间
	//s.resize(1000, 'x'); //开空间+初始化

	size_t sz = s.capacity();
	sz = s.capacity();
	cout << "capacity changed: " << sz << '\n';
	cout << "making s grow:\n";
	for (int i = 0; i < 1000; ++i)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}
}

在这里插入图片描述

8.insert()函数

//string& insert (size_t pos, const char* s);
void test_string08()
{
	string str("wo lai le");

	//1.使用易错
	// wo20%20% lai le 
	/*for (size_t i = 0; i < str.size();i++)
	{
		if (str[i] == ' ')
		{
			str.insert(i, "20%");
			i += 4;
		}
	}*/

	//2.1修正
	//wo20% lai20% le
	/*for (size_t i = 0; i < str.size();)
	{
		if (str[i] == ' ')
		{
			str.insert(i, "20%");
			i += 4;
		}
		else
		{
			++i;
		}
	}*/

	//2.2修正
	//string& erase (size_t pos = 0, size_t len = npos);
	/*for (size_t i = 0; i < str.size(); ++i)
	{
		if (str[i] == ' ')
		{
			str.insert(i, "20%");
			i += 3;
		}
	}
	cout << str << endl;

	for (size_t i = 0; i < str.size(); ++i)
	{
		if (str[i] == ' ')
		{
			str.erase(i, 1);
		}
	}
	cout << str << endl;*/

	//3.改进(以空间换时间)
	string newstr;
	for (size_t i = 0; i < str.size(); ++i)
	{
		if (str[i] != ' ')
		{
			newstr += str[i];
		}
		else
		{
			newstr += "20%";
		}
	}
	cout << newstr << endl;

	//4.replace(效率不高)
	//string& replace (size_t pos,  size_t len,  const char* s);
	for (size_t i = 0; i < str.size(); ++i)
	{
		if (str[i] == ' ')
		{
			str.replace(i, 1, "20%");
		}
	}
	cout << str << endl;
}

9.c_str()函数

const char* c_str() const;
void test_string09()
{
	string filename("test.cpp");

	FILE* fout = fopen(filename.c_str(), "r");
	assert(fout);

	char ch = fgetc(fout);
	while (ch != EOF)
	{
		cout << ch;
		ch = fgetc(fout);
	}
}
//C++与C的字符串区别
void test_string10()
{
	string filename("test.cpp");
	cout << filename << endl;
	cout << filename.c_str() << endl;

	filename += '\0';
	filename += "string.cpp";

	cout << filename << endl;
	cout << filename.c_str() << endl;
}

10.find、rfind、substr

10.1综合应用

void DealUrl(const string& url)
{
	size_t pos1 = url.find("://");
	if (pos1 == string::npos)
	{
		cout << "非法url" << endl;
		return;
	}

	string protocol = url.substr(0, pos1);
	cout << protocol << endl;

	size_t pos2 = url.find('/', pos1 + 3);
	if (pos2 == string::npos)
	{
		cout << "非法url" << endl;
		return;
	}

	string domain = url.substr(pos1 + 3, pos2 - pos1 - 3);
	cout << domain << endl;

	string uri = url.substr(pos2 + 1);
	cout << uri << endl << endl;
}
void test_string11()
{
	string filename("test.cpp.tar.zip");

	//size_t find(char c, size_t pos = 0) const;
	//size_t rfind(char c, size_t pos = npos) const;

	//size_t pos = filename.find('.');
	size_t pos = filename.rfind('.');
	if (pos != string::npos)
	{
		//string substr (size_t pos = 0, size_t len = npos) const;

		//string suff = filename.substr(pos, filename.size() - pos);
		string suff = filename.substr(pos);

		cout << suff << endl;
	}

	//协议名://域名/动作
	string url1 = "https://cplusplus.com/reference/string/string/";
	string url3 = "ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf";

	DealUrl(url1);
	DealUrl(url3);
}

10.2rfind()应用

//输出一行字符串中最后一个单词长度
void function()
{
	string str;
	//istream& getline(istream & is, string & str);
	getline(cin, str);
	size_t pos = str.rfind(' ');
	if (pos != string::npos)
	{
		cout << str.size() - pos - 1;
	}
	else
		cout << str.size() << endl;
}

11.find_first_of

size_t find_first_of (const char* s, size_t pos = 0) const;
void test_string12()
{
	string str("Please, replace the vowels in this sentence by asterisks.");
	size_t found = str.find_first_of("aeiou");
	while (found != string::npos)
	{
		str[found] = '*';
		found = str.find_first_of("aeiou", found + 1);
	}
	//遍历A--找到与B相同的字符返回位置
	cout << str << '\n';
}

12.字符串转换

void test_string13()
{
	int ival;
	double dval;
	cin >> ival >> dval;
	string istr = to_string(ival);
	string dstr = to_string(dval);
	cout << istr << endl;
	cout << dstr << endl;

	istr = "9999";
	dstr = "9999.99";
	ival = stoi(istr);
	dval = stod(dstr);
}

13.运行结果

在这里插入图片描述

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

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

相关文章

github本地修改后不想提交

本地做了修改后&#xff0c;不想提交&#xff0c;想恢复如初&#xff0c;如果直接git reset --hard 会提示你本地还有没暂存的文件。 所以可以先暂存&#xff0c;然后再回退

Linux ~ NFS 文件共享

Ubuntu 下载nfs服务软件包 sudo apt-get install nfs-kernel-server配置nfs vim /etc/exports表头表头/mnt/*指示要共享的目录*代表允许所有的网络段访问rw指示具有可读写的权限sync指示资料同步写入内存和硬盘no_root_squash客户端分享目录使用者的权限 启动rpcbind服务 …

Databend 开源周报 第 99 期

Databend 是一款现代云数仓。专为弹性和高效设计&#xff0c;为您的大规模分析需求保驾护航。自由且开源。即刻体验云服务&#xff1a;https://app.databend.cn 。 Whats On In Databend 探索 Databend 本周新进展&#xff0c;遇到更贴近你心意的 Databend 。 Flink CDC Apa…

【AudioCaps数据集】windows10下载AudioCaps数据集,附百度网盘下载链接

&#x1f525; AudioCaps是从AudioSet数据集中筛选再加工得到的数据集。 AudioCaps数据集的下载使用python的第三方库 audiocaps-download&#xff0c;根据README.md的提示&#xff0c;先进行配置下载环境&#xff1a; &#x1f4e3; AudioCaps的下载环境配置分为四步&#x…

Windows 10, version 22H2 (updated Jun 2023) 中文版、英文版下载

Windows 10, version 22H2 (updated Jun 2023) 中文版、英文版下载 请访问原文链接&#xff1a;https://sysin.org/blog/windows-10/&#xff0c;查看最新版。原创作品&#xff0c;转载请保留出处。 作者主页&#xff1a;sysin.org Windows 10 更新历史记录 Windows 10, ver…

解决vue依赖报错SockJSServer.js出现Cannot read property ‘headers‘ of null

前言 在做新的需求需要变更vue的项目代码时突然出现报错 TypeError: Cannot read property ‘headers’ of null at Server.socket.on (***/node_modules/webpack-dev-server/lib/servers/SockJSServer.js:68:32) 不清楚为什么突然出现了这个问题&#xff0c;之前在这个vue项目…

8.9 实现UDP通信

目录 write/read到send/recv 函数原型&#xff1a; 常见flags: sendto与recvfrom UDP通信的实现过程 服务器端代码、 客户端代码 Makefile write/read到send/recv 函数原型&#xff1a; ssize_t send(int sockfd, const void *buf, size_t len, int flags); ssize_t …

最优化方法(基于lingo)之 目标规划问题求解(6/6)

一、实验目的&#xff1a; 1. 练习建立实际问题的多目标规划模型。 2. 掌握用数学软件求解多目标规划的方法。 3. 实验从算法思想、实验步骤与程序、运行结果、结果分析与讨论等几方面完成。 4. 预习多目标规划的理论内容。 二、实验内容 题目&#xff1a; 建立模型并求解&…

一篇文章告诉你,全网爆款抓包工具的优劣势

前言 作为软件测试工程师&#xff0c;抓包总是不可避免&#xff1a;遇到问题要做分析需要抓包&#xff1b;发现 bug 需要定位要抓包&#xff1b;检查数据传输的安全性需要抓包&#xff1b;接口测试遇到需求不全的也需要抓包... 就因为抓包在测试工作中无处不在&#xff0c;所以…

TuyaOS 开发固件OTA配置指南

文章目录 一、固件升级配置升级信息设置配置中英文升级文案配置发布范围固件升级验证 二、固件升级发布 通过TuyaOS接入涂鸦云的产品全部默认支持固件OTA功能&#xff0c;TuyaOS设备实现固件OTA需要&#xff1a; 自定义产品创建TuyaOS嵌入式开发固件上传固件OTA配置与发布 等步…

PMP知识点汇总完善版,2023年8月考试就靠它了

第1章 整体管理 1.1 制定项目章程 是制定一份正式批准项目或阶段的文件&#xff0c;并记录能反应干系人需要和期望的初步要求的过程。由项目以外的人员批准&#xff0c;如发起人&#xff0c;批准标志项目的正式启动。 1.1.1 知识点汇总 1、由项目以外的人员批准&#xff0c;如…

Mac iterm Ctrl + V内容前后出现了0~ 1~

背景 笔者周六日加班的时候&#xff0c;被小外甥看到&#xff0c;小外甥就对电脑玩了起来&#xff0c;玩完就这样了 现象 iterm2中复制黏贴出现如下现象&#xff1a; 解决 经过了解是启用了括号粘贴&#xff0c;不得不感叹两岁小外甥这天赋真逆天啊&#xff0c;不辜负他爸…

深入浅出设计模式 - 抽象工厂模式

博主介绍&#xff1a; ✌博主从事应用安全和大数据领域&#xff0c;有8年研发经验&#xff0c;5年面试官经验&#xff0c;Java技术专家✌ Java知识图谱点击链接&#xff1a;体系化学习Java&#xff08;Java面试专题&#xff09; &#x1f495;&#x1f495; 感兴趣的同学可以收…

自动化测试框架[Cypress概述]

目录 前言&#xff1a; Cypress简介 Cypress原理 Cypress架构图 Cypress特性 各类自动化测试框架介绍 Selenium/WebDriver Karma Karma的工作流程 Nightwatch Protractor TestCafe Puppeteer 前言&#xff1a; Cypress是一个基于JavaScript的端到端自动化测试框架…

个人自我评价格式范文五篇

★个人自我评价1 工作已经进行两周多了&#xff0c;突然发现自己似乎又重蹈覆辙了&#xff0c;再一次一次的不经意中和某些人的就距离却是越来越来大&#xff0c;总是想偷一下懒&#xff0c;总是想着马马虎虎过去算了&#xff0c;没有那么精打细算过。结果不经意有些人人开始脱…

android的项目下的res文件夹下的部分文件夹介绍

1.看图 drawable文件夹下的图片是不压缩的图片 drawable-xhdpi文件夹下的图片是适合指定分辨率的图片 mipmap-xxhdpi文件夹下的图片是小型设备分辨率的图片

基于物联网、云计算建设的智慧校园云平台源码

电子班牌作为班级文化展示交流的窗口&#xff0c;可以让更多的人看到校园信息建设与班级风格相结合&#xff0c;及时传递校园信息。学生也可以通过电子班牌看到学校近期重要事件的发布&#xff0c;也可以参与回复&#xff0c;让学生及时掌握校园和班级动态。同时&#xff0c;还…

版本管理可视化工具GitKraKe安装

资源下载地址 https://download.csdn.net/download/u012796085/87953404 1 解压后安装GitKrakenSetup-7.5.5.exe 2 命令窗口进入GitKraken存放目录&#xff0c;分别执行以下语句 git clone https://gitee.com/pan13640612207/GitKraken.git cd GitKraken/ yarn install yarn…

STM32使用STM32CUBEMX配置FreeRTOS+SDIO4bit+FATFS注意事项

一、使用STM32CUBEMX配置FreeRTOSSDIO4bitFATFS注意事项&#xff1a; 以STM32F429为例&#xff1a; 1、SDIO配置 配置为4bit模式&#xff0c;此配置不是最终配置&#xff0c;后面会在代码进行修改。 2、Fatfs配置 Set Defines 选项中的配置可以默认&#xff0c;最重要注意Ad…

git配置和git合并

git配置&#xff1a; 首先下载安装git&#xff1a;https://git-scm.com/downloads/ 一路默认&#xff0c;安装完成后&#xff0c;打开文件夹C:\Users\Administrator\.ssh&#xff08;Administrator是当前用户名&#xff09;&#xff0c;在空白处点鼠标右键选择“Git Bush Her…