c++标准容器基础《string》

c++标准容器基础之string
与c语言不同,为了方便字符串的使用,c++标准容器新增了string类,而不再是之前C语言采用字符数组的形式存储字符串,这对于字符串的处理而言更加方便。总体感觉而言,c++中string类的各种函数与java类似,使用时可注意对比。

string常用函数

#include <iostream>
#include <string>  //注意string.h和string是不一样的头文件
using namespace std;

void string_lianxi()
{
	string str = "abcd";
	for (int i = 0; i < str.length(); i++)  //length()和size()基本相同
		cout << str[i];  //string和vector可以通过下标访问
	cout << endl;

	string::iterator it = str.begin();
	for (; it != str.end(); it++)
		cout << *it;    //通过迭代器访问
	cout << endl;

	string str1 = "xyz";
	str = str + str1;     //类似java,+表示两个字符串直接拼接,该句可缩写为str+=str1
	cout << str << endl;

	if (str > str1)    //两个字符串可直接比较,依据字典序
		cout << 1 << endl;
	else
		cout << 0 << endl;

	string str2 = "god";
	str.insert(3, str2);  //在str的3号位置插入str2
	cout << str << endl;
	str.insert(str.begin() + 2, str2.begin(), str2.end() - 1);  //在str的2号位置插入[str2.begin(),str2.end()-1)的部分字符串
	cout << str << endl;

	str.erase(str.begin() + 1); //删除str的1号位置的元素
	cout << str << endl;
	str.erase(str.begin() + 1, str.begin() + 5);   //删除str的1号位置到5号位置的元素,区间左开右闭
	cout << str << endl;
	str.erase(1, 2);  //删除从str中1号位置长度为2的字符串
	cout << str << endl;

	string str3 = "hello world";
	cout << str3.substr(0, 5) << endl;  //substr(pos,length)表示返回起始位置为pos,长度为length的子字符串
	cout << str3.substr(6, 5) << endl;
	cout << str3.substr(4, 4) << endl;

	cout << str.find(str1) << endl;  //str.find(str1)表示返回str1第一次在str出现的位置下标,若未出现则返回string::npos(值为-1或4294967295)
	cout << str.find(str2) << endl;
	cout << str.find(str1, 2) << endl;  //str.find(str1,2)表示从str的2号位开始检查,返回str1第一次在str出现的位置下标,若未出现则返回string::npos
	cout << str.find(str1, 3) << endl;

	cout << str.replace(1, 2, str2)<<endl;  //str.replace(pos, length, str2)表示将从str的位置为pos,长度为length的子串用str2代替
	cout << str.replace(str.begin(), str.begin() + 2, "zuoyuanlin")<<endl;  //str.replace(first,last,str1)表示将str的[first,last)用str1替换
}

猜你喜欢

转载自blog.csdn.net/shuangmu_chenglin/article/details/88425364
今日推荐