C++学习(模板string类)[6]

string

在这里插入图片描述
std::string是一个字符串类模板,定义在头文件中。它是C++标准库中提供的用于操作字符串的模板类。

std::string模板类提供了一系列成员函数和操作符重载,用于对字符串进行各种操作,例如字符串的拼接、查找、替换、插入、删除等。

以下是一些常用的std::string成员函数和操作符重载:

length() 或 size():返回字符串的长度。
empty():检查字符串是否为空。
clear():清空字符串。
c_str():返回一个以null结尾的C风格字符串。
substr(pos, len):返回从位置pos开始的长度为len的子串。
find(str, pos):在字符串中从位置pos开始查找子串str,返回第一次出现的位置。
replace(pos, len, str):用字符串str替换从位置pos开始长度为len的子串。
insert(pos, str):在位置pos插入字符串str。
erase(pos, len):从位置pos开始删除长度为len的子串。
operator+:字符串拼接。
operator==、operator!=、operator<、operator>等:字符串的比较操作。

string类中的operator[]和string类中at的区别

在C++的std::string类中,operator[]at()都可以用于访问字符串中的单个字符。它们的主要区别在于对于越界访问的处理方式。

  • operator[]:使用operator[]时,如果尝试访问越界的索引,行为是未定义的。这意味着编译器不会进行越界检查,如果访问了超出字符串长度的索引,可能会导致程序崩溃或产生不可预测的结果。因此,使用operator[]时需要自行确保索引的有效性。

  • at():与operator[]不同,at()函数会进行边界检查。如果尝试访问越界的索引,at()会抛出一个std::out_of_range异常。这使得在访问字符串中的字符时更安全,可以避免访问无效的索引。

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    // 使用operator[]访问字符
    char c1 = str[0];
    std::cout << "Using operator[]: " << c1 << std::endl;  // 输出:H
    
    // 使用at()访问字符
    try {
        char c2 = str.at(0);
        std::cout << "Using at(): " << c2 << std::endl;  // 输出:H
    } catch (const std::out_of_range& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }
    
    // 尝试访问越界索引
    try {
        char c3 = str[100];  // 越界访问
        std::cout << "Using operator[]: " << c3 << std::endl;
    } catch (const std::out_of_range& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;  // 输出:Exception caught: basic_string
    }
    
    try {
        char c4 = str.at(100);  // 越界访问
        std::cout << "Using at(): " << c4 << std::endl;
    } catch (const std::out_of_range& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;  // 输出:Exception caught: basic_string
    }
    
    return 0;
}

在上述示例中,我们首先使用operator[]at()访问字符串中的第一个字符,结果都是正常的。然后,我们尝试使用这两种方式访问越界的索引,结果显示了它们的不同行为。operator[]没有报错,而是产生了未定义的结果,而at()抛出了std::out_of_range异常,提供了更安全的访问方式。

迭代器

//一个类中四种迭代器
//iterator/const_iterator
//reverse_iterator/const_reverse_iterator

在这里插入图片描述
相比于其他容器,std::string类中的operator[]有以下几个优点,使其更适合于处理字符串:

  1. 简洁性:std::string类中的operator[]使用起来更加简洁直观。通过使用索引值,可以直接访问字符串中的单个字符,而不需要使用迭代器或其他复杂的方法。

  2. 性能:std::string类中的operator[]是通过指针算术实现的,因此在访问字符串中的字符时具有很高的性能。与使用迭代器进行遍历相比,使用operator[]可以更快地访问和修改特定位置的字符。

  3. 习惯性:std::string类中的operator[]与C-style字符串的访问方式相似,即通过索引访问字符。这使得在处理字符串时,使用operator[]更符合程序员的习惯,更容易理解和维护。

然而,需要注意的是,operator[]没有边界检查,当使用越界的索引时,会导致未定义的行为。因此,在使用operator[]时,需要自行确保索引的有效性,以避免访问无效的索引。如果需要进行边界检查,可以使用std::string类的at()函数。另外,使用迭代器遍历字符串可以提供更多的灵活性,可以在字符串中进行逐个字符的处理,或者使用迭代器的其他功能,如逆向迭代等。因此,在处理字符串时,根据具体的需求和场景,选择使用operator[]或迭代器都是有优势的。

#include<iostream>
#include<string>
#include <list>
using namespace std;

void test_string1()   //构造
{
	string s1;              //无参
	string s2("hello word");     //有参
	cout << s1 << endl;
	cout << s2 << endl;

	string s3(s2);         //拷贝  深拷贝
	cout << s3 << endl;

	string s4(s2, 6, 5);   //string (const string& str, size_t pos, size_t len = npos);
	cout << s4 << endl;    // size_t pos为拷贝开始位置   size_t len为长度  给缺省值可以  给的太长时直接拷到结尾
	                       //npos为静态成员变量 =-1 所以size_t len不给值时,npos为42亿9千万,直接拷到结尾
	string s5("hello word", 5);
	cout << s5 << endl;    //只用前五个

	string s6(100, 'x');  //用100个x
	cout << s6 << endl;    

	//cin >> s1 >> s2;      //string重载了运算符<< >>
	//cout << s1 << endl;
	//cout << s2 << endl;
}

void test_string2()  //赋值
{
	string s1;
	string s2="hello word";    //构造+拷贝构造  -》 优化为 直接构造 

	s1 = s2;
	s1 = "xxxxx";              //
	s1 = 'y';
}

void test_string3()
{
	string s1("hello word");
	cout << s1[0] << endl;
	s1[0] = 'x';           //[]为重载运算符  返回的是引用(减少拷贝,修改返回对象)
	cout << s1[0] << endl;
	cout << s1 << endl;    //s1也被改

	//遍历每一个++
	for (size_t i = 0; i < s1.size(); ++i)   //s1.length()   也可以
	{
		s1[i]++;
	}
	cout << s1 << endl;

	const string s2("word");
	for (size_t i = 0; i < s2.size(); ++i)
	{
		//s2[i]++;       //const对象会调用const  不能修改
		cout << s2[i] << ' ';
	}
	cout << endl;
	cout << s2 << endl;
}

//一个类中四种迭代器
//iterator/const_iterator
//reverse_iterator/const_reverse_iterator
void test_string4()  //迭代器
{
	string s("hello");
	string::iterator it = s.begin();
	while (it != s.end())
	{
		cout << *it << ' ';
		++it;
	}
	cout << endl;

	//范围for  自动迭代,自动判断结束  底层其实就是迭代器
	//依次取s中的每个字符,赋值给ch
	for (auto ch : s)           //如要实现修改功能 可以加上引用   auto& ch
	{
		cout << ch << " ";
	}
	cout << endl;

	list<int> lt(10, 1);    //左闭右开 end为最后一个数据的下一个位置
	list<int>::iterator lit = lt.begin();
	while (lit != lt.end())
	{
		cout << *lit << " ";
		++lit;
	}
	cout << endl;

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

void Print_string(const string& str)   //const类型使用const迭代器 不能修改
{
	string::const_iterator rit = str.begin();
	while (rit != str.end())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;

	auto t = str.rbegin();   //string::const_reverse_iterator t = str.begin();
	while (t != str.rend())
	{
		cout << *t << " ";
		++t;
	}
	cout << endl;
}

void test_string5()  //反向迭代器  rbegin rend
{
	string s("hello");
	string::reverse_iterator rit = s.rbegin();
	while (rit != s.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
	Print_string(s);
}

void test_string6()
{
	string s("hello");
	s.push_back('-');
	s.push_back('-');
	s.append("word");
	cout << s << endl;

	string str("i am");
	s += '@';
	s += "!!!";
	s += str;
	cout << s << endl;

	s.append(++str.begin(), --str.end());   //表示开始和结尾  此处即不要首尾
	cout << s << endl;

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

void test_string7()
{
	string s;
	string s1;
	cout << s1.max_size() << endl;
	cout << s.max_size() << endl;     //42yi9qianwan  是写死的

	cout << s.capacity() << endl;   //15
	cout << s1.capacity() << endl;  //15   写死的

	//扩容机制
	string st;
	st.reserve(1000);   //保留+开空间  提前开好空间避免扩容
	st.resize(1000);    //开空间+初始化(在1000后插入)  不给值是0  st.resize(1000,‘x’);  给的x
	size_t sz = st.capacity();
	cout << "capacity changed:" << sz << '\n';
	cout << "making s grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		st.push_back('c');
		if (sz != st.capacity())
		{
			sz = st.capacity();
			cout << "capacity changed:" << sz << '\n';
		}
	}
}

int main()
{
	test_string1();
	test_string2();
	test_string3();
	test_string4();
	test_string5();
	test_string6();
	test_string7();
	return 0;
}

在这里插入图片描述

string::insert

1、3、6
在这里插入图片描述

void test_string8()
{
	string str("wo lai le");    //要求在空格处插入百分号
	for(size_t i=0 ; i<str.size() ; )
	{
		if(str[i]==' ');
		str.insert(i,"20%");
		i+=4;
    }else
    {
    	++i;
    }
    cout<<str<<endl;
}
/*
	for(size_t i=0 ; i<str.size() ; ++i)
	{
		if(str[i]==' ');
		str.insert(i,"20%");
		i+=3;
    }
*/

在这里插入图片描述

string::erase


1: npos不给数值,默认删除到结尾

//先插入再删除
void test_string8()
{
	string str("wo lai le");    //要求在空格处插入百分号
	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;
}

*/

//另一种方案   空间换时间
void test_string8()
{
	string str("wo lai le");    //要求在空格处插入百分号
	string newstr;
	for(size_t i=0 ; i<str.size() ;++i )
	{
		if(str[i] != ' ');
		{
			newstr += str[i];
		}else
		{
			newstr += "20%";
		}
    }
    cout<<newstr<<endl;


*/

string::c_str

在这里插入图片描述

兼容c

void test_string9()
{
	string filename("test.cpp");
	cout<<fliename<<endl;                     //   test.cpp
	cout<<filename.c_str()<<endl;          //   test.cpp
	/*
	filename += '\0';
	filename +="string.cpp";
	cout<<fliename<<endl;                         //  test.cpp   string.cpp
	cout<<filename.c_str()<<endl;             //   test.cpp           遇见\0结束
   */

	FILE* fout = fopen(fliename.c_str() , "r");
	assert(fout);
	char ch = fgetc(fout);
	while(ch != EOF)
	{
		cout<<  ch;
		ch = fgetc(fout);
	}
}

string::find string::substr

//取后缀
void test_string10()
{
	string filename("test.cpp");
	size_t pos = filename.find('.');   //将.的位置赋值给pos
	if(pos != string::nopos)
	{
			string suff = filename.substr(pos,filename.size()-pos);  //从pos位置取filename.size()-pos长度的字符
			cout<<suff<<endl;
	}
}


void test_string11()
{
	string filename("test.cpp.tar.zip");
	size_t pos = filename.rfind('.');   //将.的位置赋值给pos
	if(pos != string::nopos)
	{
			string suff = filename.substr(pos);  //从pos位置取filename.size()-pos长度的字符
			cout<<suff<<endl;
	}
}

找url

string url="http://baidu.com/fafffd//";
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 domin = url.substr(pos1+3,pos2-pos1-3);
	cout<<domin<<endl;

	string uri = url.substr(pos+1);
	cout<<uri<<endl;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值