【C++】string的部分接口補充(swap()、replace()、suffix()、find())

swap()

swap()接口表示交換,有以下兩種編寫方式 

void test_string()
{
	string s1("hello");
	string s2("world");
	cout << s1 << "--" << s2 << endl;
	s1.swap(s2);//單純地成員變量的交換,指針交換,代價小
	cout << s1 << "--" << s2 << endl;
	swap(s1, s2); //產生了一個臨時對象,拷貝構造,再賦值,再賦值,代價大,效率低
	cout << s1 << "--" << s2 << endl;
}

兩種方法都可以實現交換,但是代價不一樣,更傾向於使用s1.swap(s2) 

 

 

replace()

replace()是string類中經常被使用的一個接口,功能是替換。下面以一個例子來說明。

void test_string1()
{
	string url = "https://blog.csdn.net/Miss_Monster";
	cout << url << endl;
	//從0開始的5個字符替換爲"http",但是代價較大。
	//如果不是一等一替換,字符需要一個一個挪動一次位置
	url.replace(0, 5, "http");
	cout <<"替換後爲:"<< url << endl;
	cout << endl;

	url[5] = '\0';//將url的第五個字符改爲'\0'
	cout << url << endl;//cout遇到'\0'不會停止
	cout <<"C形式的字符串輸出爲:"<< url.c_str() << endl;
	printf("printf輸出%s\n", url.c_str());//C形式的字符串是以'\0'結束
	cout << endl;
}

 

suffix()

suffix()接口可以理解爲獲取子字符串,常用於獲取後綴等...

之前我們也用過suffix接口,也知道這個是專門獲取後綴的,但是如果直接使用這個接口編寫的代碼是硬編碼,非常生硬,一旦字符串發生改變,這個接口的參數也要改變,適用性不強,所以我們將它與find()進行配合。

void test_string2()
{
	string file = "test.cpp";
	//硬編碼(寫死的生硬的編碼),從字符串的第4個位置開始取4個字符
	//一旦改變字符串,或者字符串很長,適用性就不普遍了,這樣就不可取
	string suffix(file, 4, 4);
	cout << suffix << endl;

	size_t pos = file.find('.');//如果找到了就返回第一次出現的位置
	if (pos != string::npos)//否則返回npos(npos是它的一個靜態成員的const變量,npos=-1)
	{
		string suffix(file, pos, file.size() - pos);
		cout << suffix << endl;
	}
}

find()

find()接口顧名思義就是查找,查找一個字符串是否在調用的字符串中出現過。

同類型的還有rfind,找最後一個出現的匹配字符串,返回的位置是從前往後數的

string getfilesuffix(const string& file)
{
	//size_t pos = file.find('.'); //返回第一次出現的位置
	size_t pos = file.rfind('.');  //返回最後一次出現的位置

	string suffix;
	if (pos != string::npos)
	{
		//suffix = file.substr(pos);	//取到最後
		suffix = file.substr(pos, file.size() - pos);//根據算出要取出的位數取
	}
	return suffix;
}
void test_string()
{
	cout << getfilesuffix("test.cpp") << endl;
	cout << getfilesuffix("test.c") << endl;

	cout << getfilesuffix("test.tar.zip") << endl;//若爲這種形式,則用rfind找最後一個後綴

	//.zip
	const string file = "test.cpp.tar.zip";
	size_t pos = file.rfind('.'); //最後一次出現的位置
	string suffix;
	if (pos != string::npos)
	{
		suffix = file.substr(pos, file.size() - pos);
	}
	cout << suffix << endl;

	//.tar
	size_t prevpos = file.rfind('.', pos - 1);//從pos-1的位置上倒着找
	if (pos != string::npos)
	{
		suffix = file.substr(prevpos, pos - prevpos);
	}
	cout << suffix << endl;

	//找域名
	string url("https://blog.csdn.net/Miss_Monster");
	cout << url << endl;
	size_t start = url.find("://");//找字符串
	if (start == string::npos)
	{
		cout << "invalid url" << endl;
		return;
	}
	start += 3;
	size_t finish = url.find('/', start);
	string address = url.substr(start, finish - start);
	cout << address << endl;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章