1. 程式人生 > >C++string 基本函式實現

C++string 基本函式實現

#include <iostream>
#include <string>
using namespace std;

//初始化-----------------------------------------------------
void test01() {
	string a;//預設建構函式
	string b("string");
	string c = "java";
	string d(b);//拷貝構造
	if (a == "")
		cout << "a==\"\"";//string a;將a初始化為 ""
	a = b + c;//將c載入b的尾部再賦值給a;
	b.append(c);//在b尾部直接加上c
	if (a == b&&d == b)
		cout << "a == b" << endl;
}
//讀取某個位置元素------------------------------------------
void test02() 
{
	string a("dasda");
	try
	{
		//[]不提供異常機制 .at()提供異常機制
		cout << a.at(222);
	}
	catch (...)
	{
		cout << "越界啦!" ;
	}

}
//string 中find rfind函式--------------------------------
void test03() {
	string a;
	a.append("asdfgas");
	//從頭往後找
	int i = a.find("as");
	cout << i << "   ";
	//從尾部往前找
	i = a.rfind("as");
	cout << i << "   ";
	//失敗返回-1
	i = a.find("ad");
	cout << i;
}
//求字串長度-----------------------------------------
void test04() {
	string s;
	string a("string");
	s = s + a;
	cout << "length=  " << s.size() << "  " << s.length();
}
//比較字串大小----------------------------
void test05() {
	string a = "hefei";
	string b = "anhui";
	string c = "anhui";
	cout<<a.compare(b)<<" "<<b.compare(a)<<" "<<b.compare(c);//輸出1 -1 0 a.cmp(b) a>b 返回1 依次類推
}
//字串在某個位置插入另一字串-------------------------------
void test06() {
	string a("mystring");
	string b = "c++";
	a.insert(1,"c++");// == a.insert(1,b),表示在第0個位置前插入  此時a=mc++ystring
	//a.insert(30, b); //error  因為30>a.size()
	a.insert(a.length(), b); // == a.size()  此時a=mc++ystringc++
	cout << a ;
}
//字串的刪除--------------------------------------------
void test07() {
	string a("c++ is difficult!");
	a.erase(6);//刪除a.at(6)及之後所有元素
	cout << a << endl;
	a.erase(3, 2);//從第a.at(3)開始連續刪除2個元素
	cout <<a.length()<<" "<<a ;
}
//字串的替換-------------------------------------
void test08() {
	string a = "learning c++";
	a.replace(3, 2, "int");//將a.at(3)開始的兩個元素替換為int
	cout << a;
}
//迭代器------------------------------------
void test09() {
	string a = "c++ is interesting!";
	for (string::iterator it = a.begin(); it != a.end();it++) {
		cout << *it;
	}
}
int main()
{
	
	test01();
	cout<<endl << "--------------------- -----------------------"<<endl;
	test02();
	cout << endl << "--------------------------------------------" << endl;
	test03();
	cout << endl << "--------------------------------------------" << endl;
	test04();
	cout << endl << "--------------------------------------------" << endl;
	test05();
	cout << endl << "--------------------------------------------" << endl;
	test06();
	cout << endl << "--------------------------------------------" << endl;
	test07();
	cout << endl << "--------------------------------------------" << endl;
	test08();
	cout << endl << "--------------------------------------------" << endl;
	test09();
	cout << endl << "--------------------------------------------" << endl;
	return 0;
}

在這裡插入圖片描述