STL & string的基本使用

这篇博客详细介绍了C++中字符串(string)的使用,包括初始化、拼接、访问单个字符、修改字符、获取长度和容量、追加字符串以及比较操作。还特别指出,编译器不支持两个常量字符串的直接相加。此外,演示了如何通过`+=`运算符实现字符串的拼接,并展示了其他实用的方法,如`size()`、`capacity()`、`c_str()`和`append()`等。

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

首先来看string字符串的使用:

int main()
{
	string s1("wanghello");
	string s2 = "helloworld";
	string s3, s4, s5,s6;
	s3 = s1 + s2;
	s4 = s1 + "lili";
	s5 = "lili" + s2;
	s6="lili"+"hello";//error
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	cout << s5 << endl;
	return 0;
}

上面这两种对字符串的定义都是正确的,可以进行两个对象之间的相加,还可以对字符串和对象相加,对对象和字符串相加,这些操作都是可以完成的,也可以打印出来结果:

在这里插入图片描述

但是有一点要注意,编译器不支持对两个常性字符串相加。

实现字符串的+=操作:(字符串中没有-=这个操作

int main()
{
	string s1("lilil");
	s1 += "hello";
	cout << s1 << endl;
	return 0;
}

string别的一些使用:

int main()
{
	string s1("lilil");
	string s2 = "helloworld";
	int len = s1.size();//计算s1的长度
	int size = s1.capacity();//计算s1的容量
	for (int i = 0; i < len; i++)//访问字符串中的单个字符
	{
		cout << s1[i] << " ";
	}
	cout << endl;
	s1[0] = 'x';//修改字符串中的字符
	cout << s1 << endl;
	const char* s = s1.c_str();//获得s1这个对象中的字符串的地址
	s1.append("hello");//追加字符串
	cout << s1 << endl;
	cout << (s1 == s2) << endl;//比较两个字符串的大小
	cout << (s1 > s2) << endl;
	cout << (s1 < s2) << endl;
	return 0;
}

注意在使用这些之前要加string这个库:

#include <string>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值