STL(Standard Template Library,标准模板库)

本文介绍了C++标准模板库(STL)中字符串(string)类型的使用方法,包括初始化、访问元素、转换为C风格字符串、复制子串及获取长度等常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       STL的从广义上讲分为三类:algorithm(算法)、container(容器)和iterator(迭代器),容器和算法通过迭代器可以进行无缝地连接。

                                                                                   

容器:用来管理一组元素

容器分类:vector(向量)、deque(列表)、list(双队列)

算法:主要由头文件<algorithm>,<numeric>和<functional>组 成

迭代器:迭代器在STL中用来将算法和容器联系起来,起着一种黏和剂的作用。

 

string是STL的字符串类型,通常用来表示字符串。

#include <iostream>
#include <exception>

using namespace std;

void StringInit()
{
	string s1;
	string s2("helloworld");
	string s3(10,'h');
	string s4(s2);
	
	cout<<s1<<endl;
	cout<<s2<<endl;
	cout<<s3<<endl;
	cout<<s4<<endl;
}

void StringAt()
{
	string s1("123455677");
	cout<<s1[1]<<endl;
	cout<<s1.at(1)<<endl;
	
	//cout<<s1[1000000]<<endl;
	
	try
	{
		cout<<s1.at(10)<<endl;
	}
	catch(exception &e)
	{
		cout<<e.what()<<endl;
	}
}

void StringStr()
{
	string s1("iiiiiiiii");
	const char *ptr =s1.c_str();	 //返回一个以'\0'结尾的字符串的首地址
	cout<<ptr<<endl;
}

void StringCopy()
{
	string s1("helloworld");
	char buf[32]={0};
	s1.copy(buf,2,5);
	cout<<buf<<endl;
}

void StringLength()
{
	string s1("helloworld");
	cout<<s1.length()<<endl;
	
	string s2;
	if(s2.empty())
	{
		cout<<"empty"<<endl;
	}
}

int main()
{
	//StringInit();
	//StringAt();
	//StringStr();
	//StringCopy();
	StringLength();
	
	return 0;
}

执行结果:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值