C++中String接口的简单介绍

相关解释已经作为注释一起写在代码中了

void TestString()
{
	string s1;					//构造空字符串
	string s2("hello world");	//构造string类对象
	string s3(5, 'a');			//用n个字符来构造string类对象
	string s4(s2);				//拷贝构造函数
	string s5(s2, 5);			//用s2中的5个字符构造心得string对象
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	cout << s5 << endl;
}


void TestStringSize()
{
	string s1("hello world");
	cout << s1.size() << endl;		//返回字符串的有效长度
	cout << s1.length() << endl;	//返回字符串的有效长度
	cout << s1.capacity() << endl;	//返回字符串的大小
	cout << s1.empty() << endl;		//判断字符串是否为空,返回bool
	s1.resize(15, 'a');				//将有效字符变为n个,多余的用字符a填充
	cout << s1 << endl;
	s1.reserve(20);					//为字符串预留空间
	s1.clear();						//清空有效字符串
	cout << s1 << endl;

}

void TestStringAccess()
{
	string s1("hello world");		//返回pos位置的字符
	cout << s1.operator[](4) << endl;
}

void TestStringChange()
{
	string s1("hello world");
	s1.push_back('a');			//尾插一个字符
	cout << s1 << endl;
	s1.append(5, 'b');			//字符串后追加n个字符b
	cout << s1 << endl;
	s1.operator+=("people");	//字符串后追加一个字符串
	cout << s1 << endl;
	s1.operator+=('b');			//字符串后追加一个字符
	cout << s1 << endl;
	int c=s1.find('b', 1);		//从pos位置往后开始找字符b,找到后返回位置
	cout << c << endl;
	int d = s1.rfind('b', 10);	//从pos位置往前开始找字符b,找到后返回位置
	cout << c << endl;
	s1.substr(2, 2);			//从pos位置开始截取n个字符返回
	
}

int main()
{
	TestString();
	TestStringSize();
	TestStringAccess();
	TestStringChange();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/q302989778/article/details/84555359