string类基本用法

//:字符串
#include <iostream>
#include <string>
using namespace std;
int main() {
	string str1;
	str1 = "1234546ssshhhhh";
	string str2 = "i love you";
	string str3 = str1 + " " + str2;
	string str5(str3);
	cout << str1 << endl;
	cout << str2 << endl;
	cout << str3 << endl;
	cout << str1[3] << endl;
	cout << str5 << endl;
	int str11 = str1.length();																//字符串长度
	int str12 = str1.size();																//字符串长度
	cout << " str1.length()= " << str11 << endl;
	cout << " str1.size()= " << str12 << endl;
	cout << " str1.empty()= " << str1.empty() << endl;										//判断是否为空
	swap(str1, str2);
	cout << " str1= " << str1 << endl;
	cout << " str2= " << str2 << endl;
	str1.push_back(48);																		//尾部添加字符
	str1.append("skk");
	str1.append("skk");																		//尾部添加字符串
	str1 += "99666";
	cout << " str1= " << str1 << endl;
	str1.assign("1234546");																	//重新赋值
	cout << " str1= " << str1 << endl;
	str1 = "2333333";
	cout << " str1= " << str1 << endl;
	for (int i = 0;i < str1.length();i++) {
		cout << " str1[" << i << "]= " << str1[i] << endl;
	}
	str1.insert(str1.begin() + 2,'6');														//插入字符
	cout << " str1= " << str1 << endl;
	str1.erase(str1.begin() + 2,str1.end()-2);												//删除区间内的字符
	cout << " str1= " << str1 << endl;
	str1 = "aaaaaaaaaa";
	str3 = "123456789123455556t";
	str1=str1.replace(str1.find("a"),9,"b");												//替换
	cout << " str1= " << str1 << endl;
	str3 = str3.replace(str3.begin() + 1, str3.begin() + 5, "!!!!!!!!!!");					//替换,不包含第二位置所指元素
	cout << " str3= " << str3 << endl;
	str3 = str3.replace(0, 1, str2, str2.find("3"), 9);										//替换,不包含第二个数字所对应元素
	cout << " str3= " << str3 << endl;
	string::size_type position;
	position = str3.find("123");															//获取特定字符串在string类中的位置
	cout << " the position is " << position << endl;
	cout << " str3.capacity()= " << str3.capacity() << endl;								//string容量
	cout << " str3.length()= " << str3.length() << endl;
	char* s=(char*)str3.data();																//将string类转换成字符数组形式,没有'\0'
	cout << s[2] << s[3] << s[4] << endl;
	str3.clear();																			//清空string元素
	cout << str3 << s[3] << endl;	
	cout << str2.max_size() << endl;														//string所能包含的最大字符数
	str2.reserve();																			//为字符串预留足够容量
	str2.resize(3);																			//重新定义大小
	cout << str2 << endl;
	cout << str2.capacity() << endl;
	string str6 = "123456789123456789123456789";
	cout << " str6= " << str6 << endl;
	str2=str6.substr(9);																	//提取字串
	cout << " str2= " << str2 << endl;
}


在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值