String的简单应用

#define _SCL_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

void main21()
{
	string s1 = "aaaa";
	string s2("bbbbb");
	string s3 = s2;
	string s4(10, 'a');
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;

}

void main22()
{
	string s1 = "asdf";
	try
	{
		for (int i = 0; i < s1.length(); i++)
		{
			cout << s1[i] << " ";//[]不会抛异常
		}
	}
	catch (...)
	{
		cout << "发生异常1!" << endl;
	}
	for (string::iterator it = s1.begin(); it != s1.end(); it++)
	{
		cout << *it << " ";
	}

	try
	{
		for (int i = 0; i < s1.length(); i++)
		{
			cout << s1.at(i) << " ";//at可以抛异常
		}
	}
	catch (...)
	{
		cout << "发生异常2!" << endl;
	}
	
}

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

	//s1===>char *
	cout << s1.c_str() << endl;

	//s1 的内容copy 到buf中
	char buf1[20] = {0};
	s1.copy(buf1, 3,0);//只给你copy3个字符,不会变成C风格的字符串。从0的位置开始拷贝
	cout << buf1 << endl;

}

//字符串的连接
void main24()
{
	string s1 = "aaa";
	string s2 = "bbb";
	s1 = s1 + s2;
	cout << s1 << endl;
	string s3 = "3333";
	string s4 = "4444";
	s3.append(s4);
	cout << s3 << endl;
}

//字符串的替换和查找
void main25()
{
	string s1 = "bmw 111 bmw 222 bmw 333 bmw 555";
	int index = s1.find("bmw", 0);
	cout << index << endl;

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

	int offindex2 = s1.find("bmw", 0);
	while (offindex2 != string::npos)
	{
		s1.replace(offindex2, 1, "BMWW");//案例2 从offindex2位置开始替换1个字符,替换为“BMW”
		offindex2 += 1;
		offindex2 = s1.find("bmw", offindex2);
	}
	cout << s1 << endl;

}

//删除字符
void main26()
{
	string s1 = "hello1 hello2 world";
	string::iterator it = find(s1.begin(), s1.end(), 'h');
	if (it != s1.end())
	{
		s1.erase(it);
	}
	cout << s1 << endl;

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

	s1.insert(0, "AAA");//在头部插入AAA
	s1.insert(s1.length(), "CCC");//在尾部插入CCC
	cout << s1 << endl;
}

//转换大小写
void main27()
{
	string s1 = "AAAbbb";
	string s2 = "aaaBBB";

	transform(s1.begin(), s1.end(), s1.begin(), toupper);
	transform(s2.begin(), s2.end(), s2.begin(), tolower);
	cout << s1 << endl;
	cout << s2 << endl;
}

void main()
{
	main27();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值