1. 程式人生 > >c++ STL 之 string

c++ STL 之 string


template<class T>
void print_elemnt(T &v)
{
	for(auto i : v)
		cout<<i<<" ";
	cout<<endl;
}

void test_string()
{
	/*
	 string的本質,處理utf-8字元
	 typedef basic_string<char> string;
	 */ 

	char tmp[] = "\x31\x32\x33\x34\x35\x36\x37";
	string a(tmp);		//字串賦值初始化
	string b(tmp,5);	//取前n個字元初始化
	string c(3,0x41);	//n個val初始化
	string d(a.begin(),a.begin()+4);	//區間初始化[,)
	string e(a);		//複製建構函式
	string f(a,2,3);	//取a中第二個位置開始的3個字元
	string g;			//不能這樣寫,因為沒有對應建構函式 string g = 'm';
	g = 'm';
	string h = f;
	
	/**
	 關於迭代器遍歷
	 遍歷string中的char,注意刪除時迭代器的失效問題
	 **/

	/**
	 關於大小、容量、再分配等
	 size() 和 length() 返回字元總數
	 max_size() 返回最大儲存個數,視系統而定,不固定
	 capacity() 當前可用容量

	 resize(size_t n, char c) 和 reserve()
	 前者重新分配大小為n個數據記憶體,如果n大於原始空間大小,用預設值或者特定值填寫大於部分;如果小於,取前n個數據
	 後者如果n大於原始記憶體,重新分配;如果n小於原始記憶體,不做任何操作。
	 **/

	//訪問資料的方式
	cout<<"The third element in a is "<<a[2]<<endl;	
	cout<<"The forth element in a is "<<a.at(3)<<endl;
	cout<<"first elemnt is "<<a.front()<<endl;
	cout<<"last element is " <<a.back()<<endl;

	//資料操作方式
	g.append(tmp);	//操作方法和建構函式引數差不多
	g += 'a';
	g += a;
	g += "fdsaf";
	cout<<"g:"<<endl;
	g.push_back('x');	//尾部新增一個元素
	print_elemnt(g);
	g.pop_back();		//尾部刪除一個元素

	g.erase(2,5);		//從索引2開始刪除5個字元 或者 刪除一個迭代器指向的字元 或者 一個區間[,)
	g.insert(2,2,'x');	//插入元素,一個字元 、一個區間 、重複插入一個字元、string物件或者其中的一部分
	h.clear();			//清空元素
	if (h.empty())		//判斷是否為空
	{
		cout<<"h is empty"<<endl;
	}
	
	//g.swap(h);		//交換兩個string物件內容
	cout<<" g: "<<g.c_str()<<endl; //獲取string物件的c字串,即以null(0)結尾。
	cout<<" g: data--"<<g.data()<<endl;		//和c_str()沒啥區別,好多人說沒有"\0",但是我看了英文文件,有"\0";其實主要看具體庫的實現。
	
	//size_t copy (char* s, size_t len, size_t pos = 0) const; //將string內容從POS開始len長度字元拷貝到s指標指向的記憶體中。
	g.find('x',0);		//在string物件中從某一個位置開始,查詢一個或者一段字元第一次出現的地方,返回第一個字元對應索引;否則返回string::npos
	g.rfind("ab");		//與find類似,查詢最後一次出現的位置

	h = "12345654";
	cout<<"find :"<<endl;
	cout<<h.find_first_of("49988")<<endl;	//搜尋string物件中的內容第一次出現在引數字串中的位置 本例返回3
	cout<<h.find_first_not_of("49988")<<endl;	//搜尋string物件中的內容第一次沒有在引數字串中出現的位置 本例返回0
	cout<<h.find_last_of("49988")<<endl;		//搜尋最後一次在引數字串中出現的位置	(查詢存在字元)	本例返回7
	cout<<h.find_last_not_of("49988")<<endl;	//搜尋最後一次在引數字串中沒有出現的位置	(查詢不存在字元)	本例返回6
	cout<<"h:substr=="<<h.substr(3,4)<<endl;	//字串操作,從位置3開始長度為4的字串構造一個string物件返回

	if (g.compare(h) != 0)		//比較字串,可以比較其中一部分,引數:npos1,len,desString,npos2,len
	{
		cout<<"g is not equal to h"<<endl;
	}

	//利用algorithm檔案進行大小寫轉換
	transform(g.begin(),g.end(),g.begin(),::toupper);
	cout<<"convert g to upper: "<<endl;
	print_elemnt(g);
	transform(g.begin(),g.end(),g.begin(),::tolower);

	//讀取內容到string
	getline(std::cin,h);	//從流中讀取內容,直到遇到指定字元為止,預設'\n';錯誤
	cout<<"input contents:"<<endl;
	print_elemnt(h);

	//顯示各元素內容
	print_elemnt(tmp);
	cout<<"a:"<<endl;
	print_elemnt(a);
	cout<<"b:"<<endl;
	print_elemnt(b);
	cout<<"c:"<<endl;
	print_elemnt(c);
	cout<<"d:"<<endl;
	print_elemnt(d);
	cout<<"e:"<<endl;
	print_elemnt(e);
	cout<<"f:"<<endl;
	print_elemnt(f);
}