ST库的string基本操作

#define _SCL_SECURE_NO_WARNINGS

#include "iostream"
using namespace std;
#include "string"
#include "algorithm"
/// string初始化
void main21()
{
	string s1 = "aaaa";
	string s2("bbbb");
	string s3 = s2; /// 通过拷贝构造函数来初始化对象

	string s4(10,'a');
	cout << "s1:" << s1 << endl;
	cout << "s2:" << s2<< endl;
	cout << "s3:" << s3 << endl;
	cout << "s4:" << s4 << endl;
}

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

	/// 迭代器
	cout << endl;

	for (string::iterator it = s1.begin(); it != s1.end(); it++)
	{
		cout << *it << " ";
	}

	cout << endl;
	try
	{
		for (int i = 0; i < s1.length()+3; i++)
		{
			cout << s1.at(i) << " "; /// 抛异常
		}
	}
	catch (...)
	{
		cout << "发生异常\n" << endl;
	}
	
}

///字符指针和String的转换
void main23()
{
	
	string s1 = "aaaabbbb";
	//s1 ==>char *

	printf("s1:%s\n", s1.c_str());
	/// char * string

	///s1 的内容copy buf中
	char buf1[128];
	s1.copy(buf1,3,0); /// 给你拷贝3个字符,不会变成C风格的字符串
	cout << "buf1:" << buf1 << endl;
}

/// string字符串的连接

void main24()
{
	string s1 = "aaaa";
	string s2 = "bbbb";
	s1 = s1 + s2;
	cout << s1 << endl;
	string s3 = "3333";
	string s4 = "4444";
	s3.append(s4);
	cout << "s3:" << s3 << endl;


}


/// 字符串的查找和替换
void main25()
{
	
	string s1 = "wem hello wem 1111 wem 2222 wem 3333";
	/// 第一次出现wbm index
	int index=s1.find("wem", 0); /// 位置下标从0开始
	cout << "index:" << index<<endl;

	// 求wbm出现的次数,每一次出现的数组下标
	int offindex = s1.find("wem", 0);
	while (offindex != string::npos)
	{
		cout << "offindex:" << offindex << endl;
		offindex = offindex + 1;
		offindex=s1.find("wem", offindex);
	}

	/// 替换  把小写wem换成WEB
	int offindex1 = s1.find("wem", 0);
	while (offindex1 != string::npos)
	{
		cout << "offindex:" << offindex1<< endl;
		s1.replace(offindex1,3,"WBM");
		offindex1 = offindex1 + 1;
		offindex1 = s1.find("wem", offindex1);
	}

	cout << "替换的结果" << s1 << endl;


}

//区间删除和插入
void main26()
{
	string s1 = "hello1 hello2 hello3";
	string::iterator it= find(s1.begin(), s1.end(), 'l');
	if (it != s1.end())
	{
		s1.erase(it);
	}

	cout << s1 << endl;

	s1.erase(s1.begin(), s1.end());//全部输出
	cout << s1 << endl;
	cout << s1.length() << endl;

	string s2 = "BBB";
	/// 插入
	s2.insert(0, "AAA");
	s2.insert(s2.length(),"CCC");
	cout << s2 << endl;
	///s2.insert

}

///String 算法
void main27()
{
	string s1 = "AAAbbb";
	/// 函数入口地址  函数对象 预定义的函数对象
	transform(s1.begin(), s1.end(), s1.begin(),toupper);

	cout << s1 << endl;

	string s2 = "AAAbbb";
	transform(s2.begin(), s2.end(),s2.begin(), tolower);

	cout << s2 << endl;
}
void main000()
{
	///main21();
	main27();
	system("pause");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值