1. 程式人生 > >C++中的string常用函式集錦

C++中的string常用函式集錦

我們直入主題,下面是我今天要講解的函式列表。

/*
1.查詢find系列
2.插入insert系列
3.提取substr
4.刪除erase
5.替換replace
*/


現在來看第一個:查詢函式。
/*
函式名	                              描述
find	               查詢
rfind	               反向查詢
find_first_of	       查詢包含子串中的任何字元,返回第一個位置
find_first_not_of      查詢不包含子串中的任何字元,返回第一個位置
find_last_of	       查詢包含子串中的任何字元,返回最後一個位置
find_last_not_of       查詢不包含子串中的任何字元,返回最後一個位置
*/
以上函式都是被過載了4次,以下是以find_first_of 函式為例說明他們的引數,其他函式和其引數一樣,也就是說總共有24個函式。
/*
size_type find_first_of(const basic_string& s, size_type pos = 0)
size_type find_first_of(const charT* s, size_type pos, size_type n)
size_type find_first_of(const charT* s, size_type pos = 0)
size_type find_first_of(charT c, size_type pos = 0) 
*/
所有的查詢函式都返回一個size_type型別,這個返回值一般都是所找到字串的位置,如果沒有找到,則返回string::npos。有一點需要特別注意,所有和string::npos的比較一定要用string::size_type來使用,不要直接使用int 或者unsigned int等型別。其實string::npos表示的是 - 1, 看看標頭檔案:
template <class _CharT, class _Traits, class _Alloc>
const basic_string<_CharT, _Traits, _Alloc>::size_type
basic_string<_CharT, _Traits, _Alloc>::npos
= basic_string<_CharT, _Traits, _Alloc>::size_type) - 1;
這裡稍後給出find的使用例項,我們先看最後面的四個。

有這樣一個需求:過濾一行開頭和結尾的所有非英文字元。看看用string 如何實現:

#include <string>  
#include <iostream>  
using namespace std;
int main() {
	string strinfo = "   //*---Hello Word!......------";
	string strset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	int first = strinfo.find_first_of(strset);
	if (first == string::npos) {
		cout << "not find any characters" << endl;
		return -1;
	}
	int last = strinfo.find_last_of(strset);
	if (last == string::npos) {
		cout << "not find any characters" << endl;
		return -1;
	}
	cout << strinfo.substr(first, last - first + 1) << endl;
	return 0;
}

/*
輸出如下:Hello Word
*/
這裡把所有的英文字母大小寫作為了需要查詢的字符集,先查詢第一個英文字母的位置,然後查詢最後一個英文字母的位置,然後用substr 來的到中間的一部分,用於輸出結果。但是個人覺得這個函式能到的地方也就那麼幾處。比如,Hello和Word中間還有一些字元呢,只能自己寫函式去查找了。所以具體問題具體對待,在思考問題時要考慮好,這個函式雖然提供給你,使你更方便的操作程式碼,但是也要想的全面,函式的功能與你面對的問題是否吻合。或者說這個函式能解決你多少問題,能不能有別的更高效的或者更方便的方法?

好了,下面來看看find函式吧,find函式是正向匹配,也就是找到第一個匹配的字元或字串。
下面我從兩個個方向來說,string中找string和char。

#include<iostream>
#include<string>
#include<algorithm>//find的標頭檔案
using namespace std;
int main()
{
	string str1 = "123456";
	//第一個是string中找string
	string str2 = "34";//能找到的
	string str3 = "364";//找不到的

	int a = str1.find(str2);
	int b = str1.find(str3);
	cout << a << endl;
	cout << b << endl;
	/*
	輸出是:
	         2
	        -1
	*/


	//第二個是string中找char
	char ch1 = '3';//能找到的
	char ch2 = '9';//找不到的

	int aa = str1.find(ch1);
	int bb = str1.find(ch2);

	cout << aa << endl;
	cout << bb << endl;
	/*
	輸出是:
	       2
	       -1
	*/
	return 0;
}

這裡可能會說,如果給的是字元陣列呢?例如:從char a[10]="123456789"中查詢字元char ch='5'或者char[5]="4567"呢?
http://www.cplusplus.com/reference/cstring/strstr/?kw=strstr   這是C plus plus 的講解

我們再來看看rfind函式吧,注意這個函式是逆向匹配的,也就是找到最後一個匹配的。

#include<iostream>
#include<string.h>
#include<string>
using namespace std;
int main()
{
	string str1="456456";

	string str2="456";
	string str3="654";

	int a=str1.rfind(str2);
	int b=str1.rfind(str3);

	cout<<a<<endl;//輸出3
	cout<<b<<endl;//輸出-1
	return 0;
}
第二個:插入函式
string& insert (size_t pos, const string& str);
string& insert (size_t pos, const string& str, size_t subpos, size_t sublen = npos);
string& insert (size_t pos, const char* s);
string& insert (size_t pos, const char* s, size_t n);	
string& insert (size_t pos,   size_t n, char c);
這是常用的過載。
#include <iostream>
#include <string>

int main ()
{
  std::string str="to be question";
  std::string str2="the ";
  std::string str3="or not to be";
  std::string::iterator it;

  // used in the same order as described above:
  str.insert(6,str2);                 // to be (the )question在str的第6個位置插入str2
  str.insert(6,str3,3,4);             // to be (not )the question在str的第6個位置插入str3的一個片段,為下標為3開始往後的4個字元
  str.insert(10,"that is cool",8);    // to be not (that is )the question
  str.insert(10,"to be ");            // to be not (to be )that is the question
  str.insert(15,3,':');               // to be not to be(:::) that is the question
  std::cout << str << '\n';
  return 0;
}

第三個:提取
string substr (size_t pos = 0, size_t len = npos) const;

比較簡單,直接看C plus plus給的例子

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                
  std::string str2 = str.substr (3,5);     // "think"
  std::size_t pos = str.find("live");      // position of "live" in str
  std::string str3 = str.substr (pos);     // get from "live" to the end
  std::cout << str2 << ' ' << str3 << '\n';//輸出:think live in details.
  return 0;
}
第四個:刪除函式
string& erase (size_t pos = 0, size_t len = npos)
iterator erase (iterator p)	
iterator erase (iterator first, iterator last)
還是看下C plus plus 的例子
// string::erase
#include <iostream>
#include <string>
int main()
{
	std::string str("This is an example sentence.");
	std::cout << str << '\n';
	// "This is an example sentence."
	str.erase(10, 8);                        
	std::cout << str << '\n';
	// "This is an sentence." 
	std::cout << str << '\n';
	// "This is a sentence."
	str.erase(str.begin() + 5, str.end() - 9); 
	std::cout << str << '\n';
	// "This sentence."
	return 0;
}

第五個:替換replace
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>//標頭檔案
using namespace std;
int main()
{
	/*函式原型:原型比較多,只寫常用的兩個
	1.template <class ForwardIterator, class T>
	void replace (ForwardIterator first, ForwardIterator last,const T& old_value, const T& new_value);
	2.basic_string& replace(size_type pos1,size_type n1,const basic_string& str);
	*/
	string str = "take a right turn";
	str.replace(7, 5, "left");//按地址從&str[7]到&str[12]的內容替換為left
	cout << str << endl;//take a left turn

	//注意,也可以使用find()來找出要在replace()中替換的位置
	string s1 = "old";
	string s2 = "mature";
	string s3 = "the old man and the sea";
	int pos = s3.find(s1);
	if (pos != string::npos)
		s3.replace(pos, s1.size(), s2);
	//上述程式碼把old換成mature

	//再舉一個例項
	int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
	vector<int> myvector(myints, myints + 8);            // 10 20 30 30 20 10 10 20
	replace(myvector.begin(), myvector.end(), 20, 99);   // 10 99 30 30 99 10 10 99
	//myvector中所有20換成99
	cout << "myvector contains:";
	for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
		cout << ' ' << *it;
	cout << '\n';
	/*輸出:
	myvector contains: 10 99 30 30 99 10 10 99
	*/
	return 0;
}