string类的基本操作

#include "iostream"
using namespace std;
//#include "algorithm"

#include "string"


void main01()
{
	//string 的初始化
	string s1 = "zhangwentao";
	string s2("liqimeng");
	string s3(10, 'a');

	//string 的遍历
	//1 数组方式
	for (int i = 0; i < s1.length(); i++)
	{
		cout << s1[i];
	}
	cout << endl;

	//2 迭代器方式
	for (string::iterator it = s1.begin(); it != s1.end(); it++)
	{
		cout << *it;
	}
	cout << endl;

	for (int j = 0; j < s1.length(); j++)
	{
		cout << s1.at(j);
	}
	cout << endl;

	//string 与字符指针的转化
	printf("%s \n", s1.c_str());     //c_str()函数用来返回字符串首地址

	char *buf = NULL;
	buf = new char[50];

	s1.copy(buf, 5, 0);               //copy() 将string中的内容拷贝出来

	buf[5] = '\0';
	cout << "-----------" << endl;
	cout << buf << endl;

	delete[] buf;
	buf = NULL;

	//string 的连接
	s3 = s1 + s2;       //1 string类已经重载好了 = 运算符
	cout << s3 << endl;

	s1.append(s2);    //2 使用append() 函数实现字符串连接
	cout << s1 << endl;

}

void main02()    //string 字符串的查找和替换
{
	string s1 = "zhang sifh ah hello zhang jfk zhang";
	int index = s1.find("zhang", 0);
	cout << index << endl;

	// 查找“zhang”出现的次数和出现的位置
	int offindex = s1.find("zhang", 0);
	while (1)                     //查找
	{
		if (offindex != string::npos)
		{
			cout << "offindex = " << offindex << endl;
			offindex += 1;
			offindex = s1.find("zhang", offindex);
		}
		else
		{
			break;
		}
	}
	offindex = s1.find("zhang", 0);
	while (1)                      // 替换
	{
		if (offindex != string::npos)
		{
			cout << "offindex = " << offindex << endl;
			s1.replace(offindex, 5, "ZHANG");
			offindex += 1;
			offindex = s1.find("zhang", offindex);
		}
		else
		{
			break;
		}
	}

	cout << "s1替换后:" << s1 << endl;

}
//
//void main03()    //插入和删除
//{
//	string s1 = "hello hello hello";
//	cout << s1.length() << endl;
//	string::iterator it = find(s1.begin(), s1.end(), "l");
//	if (it != s1.end())
//	{
//		s1.erase(it);
//	}
//	
//}

void main()
{
// main01();
	main02();
	//();
	system("pause");
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值