C++ STL string的一些基本用法

#include 
#include 
using namespace std;

void main()
{
	string s1 = "aaa";
	string s2 = "bbb";
	string s3(3,'c');

	//字符串拼接
	s1.append(s2);
	s3 += s2;
	cout << "s1:" << s1 << endl;
	cout << "s3:" << s3 << endl;

	//字符串的遍历
	//1数组方式,此方式不会抛出异常,此方式相当于s1.at(i),at()可以抛出异常
	for (int i=0;ichar*
	string s4 = "abcd";
	char *p = (char *)s4.c_str();
	printf("p:%s\n",p);
	//char*转string
	string s5 = p;
	cout << "s5:" << s5 << endl;

	//将string拷贝到char*指向的内存空间
	char buff[100] = { 0 };
	s5.copy(buff, 3, 0);//从第0个位置开始,拷贝3位到buff中
	cout << "buff:" << buff << endl;


	//字符串的查找和替换
	string s6 = "abcdefgabcdaba";

	int index = s6.find("a", 0);//从第0位开始查找a,查找不到则返回-1
	cout << "index:" << index << endl;
	//求a出现的次数,以及每一次出现的数组下标
	int offIndex = s6.find("a", 0);
	while (offIndex != string::npos)//string::npos:没找到,相当于-1
	{
		cout << "offIndex:" << offIndex << endl;
		offIndex = offIndex + 1;
		offIndex = s6.find("a", offIndex);
	}
	//将s6中的a替换为A
	int offIndex2 = s6.find("a", 0);
	while (offIndex2 != string::npos)//string::npos:没找到,相当于-1
	{
		s6.replace(offIndex2, 1, "A");//从第offIndex2位开始替换1位
		offIndex2 = offIndex2 + 1;
		offIndex2 = s6.find("a", offIndex2);
	}
	cout << "s6:" << s6 << endl;

	//删除字符串中某一字符
	string::iterator it = find(s6.begin(), s6.end(), 'A');
	if (it != s6.end())
	{
		s6.erase(it);
	}

	cout << "s6删除A以后:" << s6 << endl;
	//删除全部
	s6.erase(s6.begin(), s6.end());
	cout << "s6删除全部以后:" << s6 << endl;

	string s7 = "AAA";

	s7.insert(0, "BBB");//从第0位开始插入BBB
	cout << "s7:" << s7 << endl;

        //字符串的大小写转换
	string s8 = "AAAbbb";
	//第四个参数可以是函数的入口地址、函数对象、预定义的函数对象等
	transform(s8.begin(), s8.end(), s8.begin(), toupper);//从s8的开头至结尾,将转换的字符串放在s8的起始位置
	cout << "s8:" << s8 << endl;

	transform(s8.begin(), s8.end(), s8.begin(), tolower);
	cout << "s8:" << s8 << endl;


	system("pause");
}

 

你可能感兴趣的:(STL)