STL学习笔记(三),string

#include <iostream>
#include <string>

using namespace std;

//string赋值构造测试
int main()
{
	string str("123456789");
	char ch[] = "abcdefg";
	
	//定义一个空字符串
	string str1;

	//构造函数,全部复制
	string str2(str);

	//从str的第二个元素开始取5个字符复制给str3
	string str3(str, 2, 5);//34567

	//将ch的前5个字符复制给str4
	string str4(ch, 5);//abcde

	//将5个A组成的字符串复制给str5
	string str5(5, 'A');//AAAAA

	//将str全部复制给str6
	string str6(str.begin(), str.end());//123456789
	
	system("pause");
	return 0;
}


#include <iostream>
#include <string>

using namespace std;

//string大小和容量测试
int main()
{
	int size = 0;
	int length = 0;
	unsigned long max_size = 0;
	int capacity = 0;

	string str("123456789");
	
	string str1;
	//"" size=0,capacity=15
	str1.reserve(5);//没有重新分配内存

	str1 = str;
	
	//size=9
	size = str1.size();
	
	//调用resize()后,str1="12345"
	//str1.resize(5);

	//length=9
	length = str1.length();
	
	//max_size=4294967294
	max_size = str1.max_size();
	
	//capacity=15
	capacity = str1.capacity();

	system("pause");
	return 0;
}
#include <iostream>
#include <string>

using namespace std;

//string元素的存取
int main()
{
	const string cs("123456789");
	string s("abcde");
	char temp1=0;
	char temp2=0;
	char temp3=0;
	char temp4=0;
	char temp5=0;
	char temp6=0;

	//'c'
	temp1 = s[2];
	//'c'
	temp2 = s.at(2);

	//程序崩溃
	temp3 = s[s.length()];
	//抛出异常
	temp4 = s.at(s.length());

	//\0
	temp5 = cs[cs.length()];
	//抛出异常
	temp6 = cs.at(cs.length());

	system("pause");
	return 0;
}

#include <iostream>
#include <string>

using namespace std;

//string元素的修改
int main()
{
	string str("abcde");

	//非常量字符串的at()和[]操作返回的是字符的引用
	char &r1 = str[2];
	char &r2 = str.at(2);

	char *p = &str[3];

	r1 = 'X';
	*p = 'Y';

	//abXYe
	cout<<str<<endl;

	str = "123456";
	r1 = 'X';
	*p = 'Y';
	//12XY56
	cout<<str<<endl;

	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/u012592062/article/details/80293077