string类主要的操作

本文详细介绍了C++中标准库字符串的各种操作方法,包括初始化、赋值、取值、拼接、查找、替换、比较、子串提取及插入删除等功能,并通过具体示例展示了每种方法的使用。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;

//初始化
void test01()
{
	string s1;				//调用无参构造
	string s2(10, 'a');		//有参构造
	string s3("abcdefg");	
	string s4(s3);			//拷贝构造

	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;

}

//赋值操作
void test02()
{
	string s1;
	string s2("appp");
	s1 = "abcdef";
	cout << s1 << endl;
	s1 = s2;
	cout << s1 << endl;
	s1 = 'a';
	cout << s1 << endl;
	
	//成员方法
	s1.assign("jkl");
	cout << s1 << endl;

}

//取值操作
void test03()
{
	string s1 = "abcdefg";

	//重载[]操作符
	for (int i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " ";
	}
	cout << endl;

	for (int i = 0; i < s1.size(); i++)
	{
		cout << s1.at(i) << " ";
 	}
	cout << endl;

	//区别:[]方式 如果访问越界,直接挂了
	//at方式 访问越界 抛出out_of_range
	try
	{
		cout << s1.at(100) << endl;
	}
	catch(...)
	{
		cout << "访问越界" << endl;
	}

}

//拼接操作
void test04()
{
	string s1 = "abc";
	string s2 = "1111";
	s1 += "def";
	s1 += s2;

	cout << s1 << endl;


	string s3 = "2222";
	s2.append(s3);

	cout << s2 << endl;


	string s4 = s2 + s3;
	cout << s4 << endl;
}

//查找操作
void test05()
{
	string s1 = "abcdefghijklfg";
	//查找第一次出现的位置
	int pos = s1.find("fg");
	cout << "pos = " << pos << endl;

	//查找最后一次出现的位置
	pos = s1.rfind("fg");
	cout << "pos = " << pos << endl;
}

//替换操作
void test06()
{
	string s1 = "abcdefg";
	s1.replace(0, 2, "111");
	cout << s1 << endl;

}

//比较操作
void test07()
{
	string s1 = "abcd";
	string s2 = "abce";
	if (s1.compare(s2) == 0)
	{
		cout << "字符串相等!" << endl;
	}
	else
	{
		cout << "字符串不相等!" << endl;
	}
}

//子串操作
void test08()
{
	string s1 = "abcdefg";
	string s2 = s1.substr(1, 3);
	cout << s2 << endl;
}

//插入删除操作
void test09()
{
	string s1 = "abcdefg";
	s1.insert(3, "111");
	cout << s1 << endl;

	s1.erase(0, 2);
	cout << s1 << endl;
}

int main()
{
	//test01();
	//test02();
	//test03();
	//test04();
	//test05();
	//test06();
	//test07();
	//test08();
	test09();


	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值