C 和 C++字符串详解
From:http://blog.csdn.net/fenxinzi557/article/details/51457829
From:http://www.cnblogs.com/xFreedom/archive/2011/05/16/2048037.html
C++之string類型詳解:http://citycowboy.blog.sohu.com/50058804.html
----------------------------------------------------------------------------
CPP 字符串
? ? ? ? 之所以拋棄char*的字符串而選用C++標準程序庫中的string類,是因為他和前者比較起來,不必擔心內存是否足夠、字符串長度等等,而且作為一個類出現,他集成的操作函數足以完成我們大多數情況下(甚至是100%)的需要。我們可以用 = 進行賦值操作,== 進行比較,+ 做串聯(是不是很簡單?)。我們盡可以把它看成是C++的基本數據類型。
? ? ? ? MFC中的CString類使用起來真的非常的方便好用。但是如果離開了MFC框架,還有沒有這樣使用起來非常方便的類呢?答案是肯定的。也許有人會說,即使不用MFC框架,也可以想辦法使用MFC中的API,具體的操作方法在本文最后給出操作方法。其實,可能很多人很可能會忽略掉標準C++中string類的使用。標準C++中提供的string類得功能也是非常強大的,一般都能滿足我們開發項目時使用。
要想使用標準C++中string類,必須要包含:
#include <string>// 注意是<string>,不是<string.h>,帶.h的是C語言中的頭文件 using std::string; using std::wstring; 或 using namespace std;下面你就可以使用 string/wstring了,它們兩分別對應著char和wchar_t。string 和 wstring 的用法是一樣的。
以下只用string作介紹:
1. 聲明一個C++字符串
聲明一個字符串變量很簡單:string Str;
這樣我們就聲明了一個字符串變量,但既然是一個類,就有構造函數和析構函數。上面的聲明沒有傳入參數,所以就直接使用了string的默認的構造函數,這個函數所作的就是把Str初始化為一個空字符串。
2. String類的構造函數和析構函數
測試如下:
#include <iostream> #include <string> using namespace std; int main() {string str1 = "yesterday once more";string str2 ("my heart go on");string str3 (str1,6); // = day once morestring str4 (str1,6,3); // = daychar ch_music[] = {"Roly-Poly"};string str5 = ch_music; // = Roly-Poly string str6 (ch_music); // = Roly-Polystring str7 (ch_music,4); // = Rolystring str8 (10,'i'); // = iiiiiiiistring str9 (ch_music+5, ch_music+9); // = Polystr9.~string();//cout<<str9<<endl; // 測試輸出getchar();return 0; }
3. 字符串操作函數
這里是C++字符串的重點,先把各種操作函數羅列出來。
a) =,assign() // 賦以新值 b) swap() // 交換兩個字符串的內容 c) +=,append(),push_back() // 在尾部添加字符 d) insert() // 插入字符 e) erase() // 刪除字符 f) clear() // 刪除全部字符 g) replace() // 替換字符 h) + // 串聯字符串 i) ==,!=,<,<=,>,>=,compare() // 比較字符串 j) size(),length() // 返回字符數量 k) max_size() // 返回字符的可能最大個數 l) empty() // 判斷字符串是否為空 m) capacity() // 返回重新分配之前的字符容量 n) reserve() // 保留一定量內存以容納一定數量的字符 o) [ ], at() // 存取單一字符 p) >>,getline() // 從stream讀取某值 q) << // 將謀值寫入stream r) copy() // 將某值賦值為一個C_string s) c_str() // 將內容以C_string返回 t) data() // 將內容以字符數組形式返回 u) substr() // 返回某個子字符串 v) 查找系列函數 w) begin() end() // 提供類似STL的迭代器支持 x) rbegin() rend() // 逆向迭代器 y) get_allocator() // 返回配置器使用示例代碼:
# include <iostream> # include <string> using namespace std; int main() {string str1 = "yesterday once more";string str2 ("my heart go on");str2.swap(str1);cout<<str1<<endl; // = my heart go oncout<<str2<<endl; // = yesterday once morestring str3,str4;str3.assign(str2,3,6); // = heartstr4.assign(str2,3,string::npos); // = heart go on (從2開始到結尾賦給str4)str4.assign("gaint"); // =gaintstr4.assign("nico",5); // = nico,超出長度會發生什么。。。str4.assign(5,'x'); // = xxxxxcout<<str4<<endl;getchar();return 0; }
string的賦值
string &operator=(const string &s); // 把字符串s賦給當前字符串 string &assign(const char *s); // 用c類型字符串s賦值 string &assign(const char *s,int n); // 用c字符串s開始的n個字符賦值 string &assign(const string &s); // 把字符串s賦給當前字符串 string &assign(int n,char c); // 用n個字符c賦值給當前字符串 string &assign(const string &s,int start,int n); // 把字符串s中從start開始的n個字符賦給當前字符串 string &assign(const_iterator first,const_itertor last); // 把first和last迭代器之間的部分賦給字符串
string的連接
string &operator+=(const string &s); // 把字符串s連接到當前字符串的結尾 string &append(const char *s); // 把c類型字符串s連接到當前字符串結尾 string &append(const char *s,int n); // 把c類型字符串s的前n個字符連接到當前字符串結尾 string &append(const string &s); // 同operator+=() string &append(const string &s,int pos,int n); // 把字符串s中從pos開始的n個字符連接到當前字符串的結尾 string &append(int n,char c); // 在當前字符串結尾添加n個字符c string &append(const_iterator first,const_iterator last); // 把迭代器first和last之間的部分連接到當前字符串的結尾
string的比較
bool operator==(const string &s1,const string &s2)const; // 比較兩個字符串是否相等// 運算符">","<",">=","<=","!="均被重載用于字符串的比較; int compare(const string &s) const; // 比較當前字符串和s的大小 int compare(int pos, int n,const string &s)const; // 比較當前字符串從pos開始的n個字符組成的字符串與s的大小 int compare(int pos, int n,const string &s,int pos2,int n2)const; // 比較當前字符串從pos開始的n個字符組成的字符串與s中// pos2開始的n2個字符組成的字符串的大小 int compare(const char *s) const; int compare(int pos, int n,const char *s) const; int compare(int pos, int n,const char *s, int pos2) const; compare函數在>時返回1,<時返回-1,==時返回0
string的子串
string substr(int pos = 0,int n = npos) const; // 返回pos開始的n個字符組成的字符串
string的交換
void swap(string &s2); // 交換當前字符串與s2的值
string類的查找函數
特別注意:
find_first_of 函數最容易出錯的地方是和find函數搞混。它最大的區別就是如果在一個字符串str1中查找另一個字符串str2,如果str1中含有str2中的任何字符,則就會查找成功,而find則不同;
比如:
string str1("I am change"); string str2("about"); int k=str1.find_first_of(str2); //k返回的值是about這5個字符中任何一個首次在str1中出現的位置;查找函數列表:
int find(char c, int pos = 0) const; // 從pos開始查找字符c在當前字符串的位置 int find(const char *s, int pos = 0) const; // 從pos開始查找字符串s在當前串中的位置 int find(const char *s, int pos, int n) const; // 從pos開始查找字符串s中前n個字符在當前串中的位置 int find(const string &s, int pos = 0) const; // 從pos開始查找字符串s在當前串中的位置// 查找成功時返回所在位置,失敗返回string::npos的值 int rfind(char c, int pos = npos) const; // 從pos開始從后向前查找字符c在當前串中的位置 int rfind(const char *s, int pos = npos) const; int rfind(const char *s, int pos, int n = npos) const; int rfind(const string &s,int pos = npos) const; //從pos開始從后向前查找字符串s中前n個字符組成的字符串在當前串中的位置,//成功返回所在位置,失敗時返回string::npos的值 int find_first_of(char c, int pos = 0) const; //從pos開始查找字符c第一次出現的位置 int find_first_of(const char *s, int pos = 0) const; int find_first_of(const char *s, int pos, int n) const; int find_first_of(const string &s,int pos = 0) const; //從pos開始查找當前串中第一個在s的前n個字符組成的數組里的字符的位置。//查找失敗返回string::npos int find_first_not_of(char c, int pos = 0) const; int find_first_not_of(const char *s, int pos = 0) const; int find_first_not_of(const char *s, int pos,int n) const; int find_first_not_of(const string &s,int pos = 0) const; //從當前串中查找第一個不在串s中的字符出現的位置,//失敗返回string::npos int find_last_of(char c, int pos = npos) const; int find_last_of(const char *s, int pos = npos) const; int find_last_of(const char *s, int pos, int n = npos) const; int find_last_of(const string &s,int pos = npos) const; int find_last_not_of(char c, int pos = npos) const; int find_last_not_of(const char *s, int pos = npos) const; int find_last_not_of(const char *s, int pos, int n) const; int find_last_not_of(const string &s,int pos = npos) const;//find_last_of和find_last_not_of與find_first_of和find_first_not_of相似,只不過是從后向前查找
查找字符串a是否包含子串b
不是用 strA.find(strB) > 0 而是 strA.find(strB) != string:npos
string::size_type pos = strA.find(strB);
if(pos != string::npos){}
-------------------------------------------
int idx = str.find("abc");
if (idx == string::npos)
...
上述代碼中,idx的類型被定義為int,這是錯誤的,即使定義為 unsigned int 也是錯的,它必須定義為 string::size_type。
npos 是這樣定義的: static const size_type npos = -1;
因為 string::size_type (由字符串配置器 allocator 定義) 描述的是 size,故需為無符號整數型別。因為缺省配置器以型別 size_t 作為 size_type,于是 -1 被轉換為無符號整數型別,npos 也就成了該型別的最大無符號值。不過實際數值還是取決于型別 size_type 的實際定義。不幸的是這些最大值都不相同。事實上,(unsigned long)-1 和 (unsigned short)-1 不同(前提是兩者型別大小不同)。因此,比較式 idx == string::npos 中,如果 idx 的值為-1,由于 idx 和字符串string::npos 型別不同,比較結果可能得到 false。
要想判斷 find() 的結果是否為npos,最好的辦法是直接比較:
if (str.find("abc") == string::npos) { ... }
錯誤:if(str.find("abc") )?
注:找不到abc會返回-1,不為0為True。0為False?
---------------------------------------------------------------------------------------------------------
使用示例代碼:
find 函數 返回類型 size_type string s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i"); string flag; string::size_type position;//find 函數 返回jk 在s 中的下標位置 position = s.find("jk"); if (position != s.npos) //如果沒找到,返回一個特別的標志c++中用npos表示,我這里npos取值是4294967295, {cout << "position is : " << position << endl; } else {cout << "Not found the flag" + flag; } //find 函數 返回flag 中任意字符 在s 中第一次出現的下標位置 flag = "c"; position = s.find_first_of(flag); cout << "s.find_first_of(flag) is : " << position << endl;//從字符串s 下標5開始,查找字符串b ,返回b 在s 中的下標 position=s.find("b",5); cout<<"s.find(b,5) is : "<<position<<endl;//查找s 中flag 出現的所有位置。 flag="a"; position=0; int i=1; while((position=s.find_first_of(flag,position))!=string::npos) {//position=s.find_first_of(flag,position);cout<<"position "<<i<<" : "<<position<<endl;position++;i++; }//查找flag 中與s 第一個不匹配的位置 flag="acb12389efgxyz789"; position=flag.find_first_not_of (s); cout<<"flag.find_first_not_of (s) :"<<position<<endl;//反向查找,flag 在s 中最后出現的位置 flag="3"; position=s.rfind (flag); cout<<"s.rfind (flag) :"<<position<<endl;說明:
- 1. 如果string sub = ”abc“;string s = ”cdeabcigld“;s.find(sub) , s.rfind(sub) 這兩個函數如果完全匹配才返回匹配的索引,即:當s中含有abc三個連續的字母時才返回當前索引。s.find_first_of(sub), s.find_first_not_of(sub), s.find_last_of(sub), s.find_last_not_of(sub) 這四個函數,查找s中含有sub中任意字母的索引。
- 2. 如果沒有查詢到,則返回string::npos,這是一個很大的數,其值不需要知道。
string類的替換函數
string &replace(int p0, int n0,const char *s); // 刪除從p0開始的n0個字符,然后在p0處插入串s string &replace(int p0, int n0,const char *s, int n);// 刪除p0開始的n0個字符,然后在p0處插入字符串s的前n個字符 string &replace(int p0, int n0,const string &s); // 刪除從p0開始的n0個字符,然后在p0處插入串s string &replace(int p0, int n0,const string &s, int pos, int n); // 刪除p0開始的n0個字符,然后在p0處插入串s中從pos開始的n個字符 string &replace(int p0, int n0,int n, char c); // 刪除p0開始的n0個字符,然后在p0處插入n個字符c string &replace(iterator first0, iterator last0,const char *s); // 把[first0,last0)之間的部分替換為字符串s string &replace(iterator first0, iterator last0,const char *s, int n); // 把[first0,last0)之間的部分替換為s的前n個字符 string &replace(iterator first0, iterator last0,const string &s); // 把[first0,last0)之間的部分替換為串s string &replace(iterator first0, iterator last0,int n, char c); // 把[first0,last0)之間的部分替換為n個字符c string &replace(iterator first0, iterator last0,const_iterator first, const_iterator last); //把[first0,last0)之間的部分替換成[first,last)之間的字符串
string類的插入函數
string &insert(int p0, const char *s); string &insert(int p0, const char *s, int n); string &insert(int p0,const string &s); string &insert(int p0,const string &s, int pos, int n); //前4個函數在p0位置插入字符串s中pos開始的前n個字符 string &insert(int p0, int n, char c); // 此函數在p0處插入n個字符c iterator insert(iterator it, char c); // 在it處插入字符c,返回插入后迭代器的位置 void insert(iterator it, const_iterator first, const_iterator last); // 在it處插入[first,last)之間的字符 void insert(iterator it, int n, char c); // 在it處插入n個字符c
string類的刪除函數
iterator erase(iterator first, iterator last); // 刪除[first,last)之間的所有字符,返回刪除后迭代器的位置 iterator erase(iterator it); // 刪除it指向的字符,返回刪除后迭代器的位置 string &erase(int pos = 0, int n = npos); // 刪除pos開始的n個字符,返回修改后的字符串
string類的迭代器處理
string類提供了向前和向后遍歷的迭代器iterator,迭代器提供了訪問各個字符的語法,類似于指針操作,迭代器不檢查范圍。 用string::iterator或string::const_iterator聲明迭代器變量,const_iterator不允許改變迭代的內容。 常用迭代器函數有: const_iterator begin()const; iterator begin(); // 返回string的起始位置 const_iterator end()const; iterator end(); // 返回string的最后一個字符后面的位置 const_iterator rbegin()const; iterator rbegin(); // 返回string的最后一個字符的位置 const_iterator rend()const; iterator rend(); // 返回string第一個字符位置的前面 rbegin和rend用于從后向前的迭代訪問,通過設置迭代器string::reverse_iterator,string::const_reverse_iterator實現
string類的字符操作
const char &operator[](int n)const; const char &at(int n)const; char &operator[](int n); char &at(int n);operator[]和at()均返回當前字符串中第n個字符的位置, 但at函數提供范圍檢查,當越界時會拋出out_of_range異常,下標運算符[]不提供檢查訪問。const char *data()const; //返回一個非null終止的c字符數組 const char *c_str()const; //返回一個以null終止的c字符串 int copy(char *s, int n, int pos = 0) const;//把當前串中以pos開始的n個字符拷貝到以s為起始位置的字符數組中,返回實際拷貝的數目
string的特性描述
int capacity()const; // 返回當前容量(即string中不必增加內存即可存放的元素個數) int max_size()const; // 返回string對象中可存放的最大字符串的長度 int size()const; // 返回當前字符串的大小 int length()const; // 返回當前字符串的長度 bool empty()const; // 當前字符串是否為空 void resize(int len,char c); // 把字符串當前大小置為len,并用字符c填充不足的部分
string類的輸入輸出操作
string類重載運算符operator>>用于輸入,同樣重載運算符operator<<用于輸出操作。 函數getline(istream &in,string &s);用于從輸入流in中讀取字符串到s中,以換行符'\n'分開。
字符串流處理
通過定義ostringstream和istringstream變量實現,在#include <sstream>頭文件中
string input("hello,this is a test"); istringstream is(input); string s1,s2,s3,s4; is>>s1>>s2>>s3>>s4; //s1="hello,this",s2="is",s3="a",s4="test" ostringstream os; os<<s1<<s2<<s3<<s4; cout<<os.str();示例代碼:
#include <iostream> #include "string" using namespace std; //字符串初始化 void strInit() { cout << "字符串初始化:" <<endl; string s1 = "abcdefg"; //初始化方式1 string s2("abcdefg"); //初始化方式2 string s3 = s2; //通過拷貝構造函數 初始化s3 string s4(7,'s'); //初始化7個s的字符串 cout << "s1 = "<< s1 << endl; cout << "s2 = "<< s2 << endl; cout << "s3 = "<< s3 << endl; cout << "s4 = "<< s4 << endl; } //字符串遍歷 void strErgo() { cout << "字符串遍歷:" <<endl; string s1 = "abcdefg"; //初始化字符串 //通過數組方式遍歷 cout << "1、通過數組方式遍歷:" <<endl; for (int i = 0; i < s1.length(); i++) { cout << s1[i] << " "; } cout << endl; //通過迭代器遍歷 cout << "2、通過迭代器遍歷:" <<endl; for(string::iterator it = s1.begin(); it!= s1.end(); it++) { cout << *it << " "; } cout << endl; //通過at()方式遍歷 cout << "3、通過at()方式遍歷:" <<endl; for (int i = 0; i < s1.length(); i++) { cout << s1.at(i) << " "; //此方式可以在越界時拋出異常 } cout << endl; } //字符指針和字符串的轉換 void strConvert() { cout << "字符指針和字符串的轉換:" <<endl; string s1 = "abcdefg"; //初始化字符串 cout << "string轉換為char*:" <<endl; //string轉換為char* cout << s1.c_str() <<endl; //s1.c_str()即為s1的char *形式 cout << "char*獲取string內容:" <<endl; //char*獲取string內容 char buf[64] = {0}; s1.copy(buf, 7);//復制7個元素 cout << buf <<endl; } //字符串連接 void strAdd() { cout << "字符串連接:" <<endl; cout << "方式1:" <<endl; string s1 = "123"; string s2 = "456"; s1 += s2; cout << "s1 = "<< s1 << endl; cout << "方式2:" <<endl; string s3 = "123"; string s4 = "456"; s3.append(s4); cout << "s3 = "<< s3 << endl; } int main() { //初始化 strInit(); cout << endl; //遍歷 strErgo(); cout << endl; //字符指針類型和字符串轉換 strConvert(); cout << endl; //字符串連接 strAdd(); cout << endl; system("pause"); return 0; }
4. 下面詳細字符串操作函數
C++字符串和C字符串的轉換
C ++ 提供的由 C++ 字符串 得到對應的 C_string 的方法是使用 data()、c_str() 和 copy(),其中,data() 以字符數組的形式返回字符串內容,但并不添加’\0’。c_str() 返回一個以‘\0’結尾的字符數組,而 copy() 則把字符串的內容復制或寫入既有的c_string或字符數組內。C++字符串并不以’\0’結尾。我的建議是在程序中能使用C++ 字符串就使用,除非萬不得已不選用 c_string。
大小和容量函數
一個C++字符串存在三種大小:
a)現有的字符數,函數是size()和length(),他們等效。Empty()用來檢查字符串是否為空。
b)max_size() 這個大小是指當前C++字符串最多能包含的字符數,很可能和機器本身的限制或者字符串所在位置連續內存的大小有關系。我們一般情況下不用關心他,應該大小足夠我們用的。但是不夠用的話,會拋出length_error異常c)capacity()重新分配內存之前 string所能包含的最大字符數。這里另一個需要指出的是reserve()函數,這個函數為string重新分配內存。重新分配的大小由其參數決定,默認參數為0,這時候會對string進行非強制性縮減。
還有必要再重復一下C++字符串和C字符串轉換的問題,許多人會遇到這樣的問題,自己做的程序要調用別人的函數、類什么的(比如數據庫連接函數Connect(char*,char*)),但別人的函數參數用的是char*形式的,而我們知道,c_str()、data()返回的字符數組由該字符串擁有,所以是一種const char*,要想作為上面提及的函數的參數,還必須拷貝到一個char*,而我們的原則是能不使用C字符串就不使用。那么,這時候我們的處理方式是:如果此函數對參數(也就是char*)的內容不修改的話,我們可以這樣Connect((char*)UserID.c_str(), (char*)PassWD.c_str()),但是這時候是存在危險的,因為這樣轉換后的字符串其實是可以修改的(有興趣地可以自己試一試),所以我強調除非函數調用的時候不對參數進行修改,否則必須拷貝到一個char*上去。
當然,更穩妥的辦法是無論什么情況都拷貝到一個char*上去。同時我們也祈禱現在仍然使用C字符串進行編程的高手們(說他們是高手一點兒也不為過,也許在我們還穿開襠褲的時候他們就開始編程了,哈哈…)寫的函數都比較規范,那樣我們就不必進行強制轉換了。
元素存取
? ? ? ? 我們可以使用下標操作符[]和函數at()對元素包含的字符進行訪問。但是應該注意的是操作符[]并不檢查索引是否有效(有效索引0~str.length()),如果索引失效,會引起未定義的行為。而at()會檢查,如果使用 at()的時候索引無效,會拋出out_of_range異常。
? ? ? ? 有一個例外不得不說,const string a;的操作符[]對索引值是a.length()仍然有效,其返回值是’\0’。其他的各種情況,a.length()索引都是無效的。
舉例如下:
const string Cstr(“const string”); string Str(“string”); Str[3]; // ok Str.at(3); // ok Str[100]; // 未定義的行為 Str.at(100); // throw out_of_range Str[Str.length()] // 未定義行為 Cstr[Cstr.length()] // 返回 ‘\0’ Str.at(Str.length()); // throw out_of_range Cstr.at(Cstr.length()) // throw out_of_range string str1 = "Iphone 5"; cout<<str1[2]<<endl; // = h cout<<str1.at(4)<<endl; // = nstring stuff; getline(cin,stuff); // 輸入一行字符賦值給stuff getline(cin,stuff,'!'); // 輸入一行字符以“!”結束 cout<<stuff<<endl;不贊成類似于下面的引用或指針賦值: char& r=s[2]; char* p= &s[3]; 因為一旦發生重新分配,r,p立即失效。避免的方法就是不使用。
比較函數
? ? ? ? C ++字符串支持常見的比較操作符(>,>=,<,<=,==,!=),甚至支持string與C-string的比較(如 str<”hello”)。在使用>,>=,<,<=這些操作符的時候是根據“當前字符特性”將字符按字典順序進行逐一得比較。字典排序靠前的字符小,比較的順序是從前向后比較,遇到不相等的字符就按這個位置上的兩個字符的比較結果確定兩個字符串的大小。同時,string (“aaaa”) <string(aaaaa)。? ? ? ? 另一個功能強大的比較函數是成員函數compare()。他支持多參數處理,支持用索引值和長度定位子串來進行比較。他返回一個整數來表示比較結果,返回值意義如下:0-相等〉0-大于 <0-小于。
舉例如下:
string s(“abcd”); s.compare(“abcd”); // 返回0 s.compare(“dcba”); // 返回一個小于0的值 s.compare(“ab”); // 返回大于0的值 s.compare(s); // 相等 s.compare(0,2,s,2,2); // 用”ab”和”cd”進行比較小于零 s.compare(1,2,”bcx”,2); // 用”bc”和”bc”比較。 也可以使用STL的比較算法。
更改字符串內容
這在字符串的操作中占了很大一部分。首先講賦值,第一個賦值方法當然是使用操作符=,新值可以是string(如:s=ns) 、c_string(如:s=”gaint”)甚至單一字符(如:s=’j’)。還可以使用成員函數assign(),這個成員函數可以使你更靈活的對字符串賦值。
舉例如下:
s.assign(str); // 不說 s.assign(str,1,3); // 如果str是”iamangel” 就是把”ama”賦給字符串 s.assign(str,2,string::npos); // 把字符串str從索引值2開始到結尾賦給s s.assign(“gaint”); // 不說 s.assign(“nico”,5); // 把’n’ ‘I’ ‘c’ ‘o’ ‘\0’賦給字符串 s.assign(5,’x’); // 把五個x賦給字符串把字符串清空的方法有三個:s=””; s.clear(); s.erase();string提供了很多函數用于插入(insert)、刪除(erase)、替換(replace)、增加字符。
先說增加字符(這里說的增加是在尾巴上),函數有 +=、append()、push_back()。
舉例如下:
s+=str; // 加個字符串 s+=”my name is jiayp”; // 加個C字符串 s+=’a’; // 加個字符 s.append(str); s.append(str,1,3); // 不解釋了同前面的函數參數assign的解釋 s.append(str,2,string::npos) // 不解釋了 s.append(“my name is jiayp”); s.append(“nico”,5); s.append(5,’x’); s.push_back(‘a’); // 這個函數只能增加單個字符對STL熟悉的理解起來很簡單也許你需要在string中間的某個位置插入字符串,這時候你可以用insert()函數,這個函數需要你指定一個安插位置的索引,被插入的字符串將放在這個索引的后面。s.insert(0,”my name”);
s.insert(1,str);
這種形式的insert()函數不支持傳入單個字符,這時的單個字符必須寫成字符串形式(讓人惡心)。既然你覺得惡心,那就不得不繼續讀下面一段話:為了插入單個字符,insert()函數提供了兩個對插入單個字符操作的重載函數:insert(size_type index,size_type num,chart c)和insert(iterator pos,size_type num,chart c)。其中size_type是無符號整數,iterator是char*,所以,你這么調用insert函數是不行的:insert(0,1, ’j’);這時候第一個參數將轉換成哪一個呢?所以你必須這么寫:insert((string::size_type)0,1,’j’)!第二種形式指出了使用迭代器安插字符的形式,在后面會提及。順便提一下,string有很多操作是使用STL的迭代器的,他也盡量做得和STL靠近。
刪除函數erase()的形式也有好幾種(真煩!),替換函數replace()也有好幾個。
舉例如下:
string s = "il8n"; s.replace(1,2,”nternationalizatio”); // 從索引1開始的2個替換成后面的C_string s.erase(13); // 從索引13開始往后全刪除 s.erase(7,5); // 從索引7開始往后刪5個
提取子串和字符串連接
題取子串的函數是:substr(),形式如下:
s.substr(); // 返回s的全部內容 s.substr(11); // 從索引11往后的子串 s.substr(5,6); // 從索引5開始6個字符把兩個字符串結合起來的函數是+。
輸入輸出操作
- 1. >> 從輸入流讀取一個string。
- 2. << 把一個string寫入輸出流。
另一個函數就是getline(),他從輸入流讀取一行內容,直到遇到分行符或到了文件尾。
搜索與查找
查找函數很多,功能也很強大,包括了:
find() rfind() find_first_of() find_last_of() find_first_not_of() find_last_not_of()這些函數返回符合搜索條件的字符區間內的第一個字符的索引,沒找到目標就返回npos。
所有的函數的參數說明如下:
第一個參數是被搜尋的對象。第二個參數(可有可無)指出string內的搜尋起點索引,第三個參數(可有可無)指出搜尋的字符個數。比較簡單,不多說不理解的可以向我提出,我再仔細的解答。當然,更加強大的STL搜尋在后面會有提及。
最后再說說npos的含義,string::npos的類型是string::size_type,所以,一旦需要把一個索引與npos相比,這個索引值必須是string::size_type類型的,更多的情況下,我們可以直接把函數和npos進行比較(如:if(s.find(“jia”)== string::npos))。
使用示例代碼:
# include <iostream> # include <string>using namespace std; int main() {string str = "when i was young, i listen to radio.";string::size_type position;position = str.find("listen");if (position != str.npos) //npos是個很大的數,如果沒找到就會返回npos的值給position{cout<<"第一次出現的下標是:"<<position<<endl;}//從字符串下標9開始,查找字符串you,返回you 在str中的下標position = str.find("you",9);cout<<"str.find("you",9")is:"<<position<<endl;//查找子串出現的所有位置string substr = "i";position = 0;int i = 1;while((position = str.find_first_of(substr,position)) != string::npos){cout<<"position "<<i++<<position<<endl;position++;}//反向查找子串在str中最后出現的位置string flag = "to";position = str.rfind(flag);cout<<"str.rfind(flag):"<<position<<endl;getchar();return 0; }
begin() end()? ? //提供類似STL的迭代器支持
# include <iostream> # include <string> # include <algorithm> using namespace std; int main() {string str;str.push_back('Q');str.push_back('A');sort(str.begin(),str.end());string::iterator itstr = str.begin();for ( ; itstr != str.end(); itstr++){cout<<*itstr;} //str.pop_back();getchar();return 0; //輸出AQ }rbegin() rend()? ? ?// 逆向迭代器
get_allocator()? ? ?// 返回配置器
string 函數列表
| 函數名 | 描述 |
| begin | 得到指向字符串開頭的Iterator |
| end | 得到指向字符串結尾的Iterator |
| rbegin | 得到指向反向字符串開頭的Iterator |
| rend | 得到指向反向字符串結尾的Iterator |
| size | 得到字符串的大小 |
| length | 和size函數功能相同 |
| max_size | 字符串可能的最大大小 |
| capacity | 在不重新分配內存的情況下,字符串可能的大小 |
| empty | 判斷是否為空 |
| operator[] | 取第幾個元素,相當于數組 |
| c_str | 取得C風格的const char*字符串 |
| data | 取得字符串內容地址 |
| operator= | 賦值操作符 |
| reserve | 預留空間 |
| swap | 交換函數 |
| insert | 插入字符 |
| append | 追加字符 |
| push_back | 追加字符 |
| operator+= | +=?操作符 |
| erase | 刪除字符串 |
| clear | 清空字符容器中所有內容 |
| resize | 重新分配空間 |
| assign | 和賦值操作符一樣 |
| replace | 替代 |
| copy | 字符串到空間 |
| find | 查找 |
| rfind | 反向查找 |
| find_first_of | 查找包含子串中的任何字符,返回第一個位置 |
| find_first_not_of | 查找不包含子串中的任何字符,返回第一個位置 |
| find_last_of | 查找包含子串中的任何字符,返回最后一個位置 |
| find_last_not_of | 查找不包含子串中的任何字符,返回最后一個位置 |
| substr | 得到字串 |
| compare | 比較字符串 |
| operator+ | 字符串鏈接 |
| operator== | 判斷是否相等 |
| operator!= | 判斷是否不等于 |
| operator< | 判斷是否小于 |
| operator>> | 從輸入流中讀入字符串 |
| operator<< | 字符串寫入輸出流 |
| getline | 從輸入流中讀入一行 |
C 字符串
1. 字符串操作
strcpy(p, p1) // 復制字符串 strncpy(p, p1, n) // 復制指定長度字符串 strcat(p, p1) // 附加字符串 strncat(p, p1, n) // 附加指定長度字符串 strlen(p) // 取字符串長度 strcmp(p, p1) // 比較字符串 strcasecmp(const char* s1, const char* s2) // 忽略大小寫比較字符串 strncasecmp(const char* s1, const char* s2, size_t n) // 忽略大小寫比較字符串 strncmp(p, p1, n) // 比較指定長度字符串 strchr(p, c) // 在字符串中查找指定字符 strrchr(p, c) // 在字符串中反向查找 strstr(p, p1) // 查找字符串 strpbrk(p, p1) // 以目標字符串的所有字符作為集合,在當前字符串查找該集合的任一元素 strspn(p, p1) // 以目標字符串的所有字符作為集合,在當前字符串查找不屬于該集合的任一元素的偏移 strcspn(p, p1) // 以目標字符串的所有字符作為集合,在當前字符串查找屬于該集合的任一元素的偏移 * 具有指定長度的字符串處理函數在已處理的字符串之后填補零結尾符
2. 字符串到數值類型的轉換?
strtod(p, ppend) // 從字符串 p 中轉換 double 類型數值,并將后續的字符串指針存儲到 ppend 指向的 char* 類型存儲。 strtol(p, ppend, base) // 從字符串 p 中轉換 long 類型整型數值,base 顯式設置轉換的整型進制,// 設置為 0 以根據特定格式判斷所用進制,0x, 0X 前綴以解釋為十六進制格式整型,0前綴以解釋為八進制格式整型 atoi(p) // 字符串轉換到 int 整型 atof(p) // 字符串轉換到 double 符點數 atol(p) // 字符串轉換到 long 整型
3. 字符檢查
isalpha() // 檢查是否為字母字符 isupper() // 檢查是否為大寫字母字符 islower() // 檢查是否為小寫字母字符 isdigit() // 檢查是否為數字 isxdigit() // 檢查是否為十六進制數字表示的有效字符 isspace() // 檢查是否為空格類型字符 iscntrl() // 檢查是否為控制字符 ispunct() // 檢查是否為標點符號 isalnum() // 檢查是否為字母和數字 isprint() // 檢查是否是可打印字符 isgraph() // 檢查是否是圖形字符,等效于 isalnum() | ispunct()
4. 函數原型
strcpy 函數
原型:char * strcpy ( char * destination, const char * source )
功能:將字符串source拷貝到字符串destination中?
注意:在定義數組時,字符數組1的字符串長度必須大于或等于字符串2的字符串長度。不能用賦值語句將一個字符串常量或字符數組直接賦給一個字符數組。所有字符串處理函數都包含在頭文件string.h中。
strncpy 函數
原型:char * strncpy ( char * destination, const char * source, size_t num );
功能:將字符串source中前num個字符拷貝到字符串destination中?
運行結果:Comnghua?
注意:字符串source中前numchars個字符將覆蓋掉字符串destination中前numchars個字符!
strcat 函數
原型:char * strcat ( char * destination, const char * source );
功能:將字符串source接到字符串destination的后面
運行結果:Tsinghua Computer
注意:在定義字符數組1的長度時應該考慮字符數組2的長度,因為連接后新字符串的長度為兩個字符串長度之和。進行字符串連接后,字符串1的結尾符將自動被去掉,在結尾串末尾保留新字符串后面一個結尾符。
strncat 函數
原型:char * strncat ( char * destination, const char * source, size_t num );
功能:將字符串source的前num個字符接到字符串destination的后面
運行結果:Tsinghua Com
strcmp 函數
原型:int strcmp(const char * firststring, const char * secondstring);
功能:比較兩個字符串 firststring 和 secondstring?
運行結果是:Buffer 2 is less than buffer 1??
? ? ? ? ? ?Buffer 2 is greater than buffer 3
strlen 函數
原型:size_t strlen ( const char * str );
功能:統計字符串 str 中字符的個數
運行結果The length of the string is x (x為你輸入的字符總數字)
注意:strlen函數的功能是計算字符串的實際長度,不包括'\0'在內。另外,strlen函數也可以直接測試字符串常量的長度,如:strlen("Welcome")。
其他函數
void *memset(void *dest, int c, size_t count);將dest前面count個字符置為字符c. 返回dest的值. void *memmove(void *dest, const void *src, size_t count);從src復制count字節的字符到dest. 如果src和dest出現重疊, 函數會自動處理. 返回dest的值. void *memcpy(void *dest, const void *src, size_t count);從src復制count字節的字符到dest. 與memmove功能一樣, 只是不能處理src和dest出現重疊. 返回dest的值. const void * memchr ( const void * buf, int c, size_t count);void * memchr ( void * buf, int c, size_t count); 在buf前面count字節中查找首次出現字符c的位置. 找到了字符c或者已經搜尋了count個字節, 查找即停止.操作成功則返回buf中首次出現c的位置指針, 否則返回NULL.void *_memccpy(void *dest, const void *src, int c, size_t count);從src復制0個或多個字節的字符到dest. 當字符c被復制或者count個字符被復制時, 復制停止. 如果字符c被復制, 函數返回這個字符后面緊挨一個字符位置的指針. 否則返回NULL. int memcmp(const void *buf1, const void *buf2, size_t count);比較buf1和buf2前面count個字節大小. 返回值< 0, 表示buf1小于buf2; 返回值為0, 表示buf1等于buf2; 返回值> 0, 表示buf1大于buf2. int memicmp(const void *buf1, const void *buf2, size_t count);比較buf1和buf2前面count個字節. 與memcmp不同的是, 它不區分大小寫. 返回值同上. char *strrev(char *string); 將字符串string中的字符順序顛倒過來. NULL結束符位置不變. 返回調整后的字符串的指針. char *_strupr(char *string); 將string中所有小寫字母替換成相應的大寫字母, 其它字符保持不變. 返回調整后的字符串的指針. char *_strlwr(char *string); 將string中所有大寫字母替換成相應的小寫字母, 其它字符保持不變. 返回調整后的字符串的指針. char *strchr(const char *string, int c); 查找字 串string中首次出現的位置, NULL結束符也包含在查找中. 返回一個指針, 指向字符c在字符串string中首次出現的位置,如果沒有找到, 則返回NULL.char *strrchr(const char *string, int c);查找字符c在字符串string中最后一次出現的位置, 也就是對string進行反序搜索, 包含NULL結束符. 返回一個指針, 指向字符c在字符串string中最后一次出現的位置, 如果沒有找到, 則返回NULL. char *strstr(const char *string, const char *strSearch);在字符串string中查找strSearch子串. 返回子串strSearch在string中首次出現位置的指針. 沒有找到子串strSearch, 則返回NULL. 如果子串strSearch為空串, 函數返回string值.char *strdup(const char *strSource); 函數運行中會自己調用malloc函數為復制strSource字符串分配存儲空間, 然后再將strSource復制到分配到的空間中. 注意要及時釋放這個分配的空間。返回一個指針, 指向為復制字符串分配的空間; 如果分配空間失敗, 則返回NULL值. char *strcat(char *strDestination, const char *strSource);將源串strSource添加到目標串strDestination后面, 并在得到的新串后面加上NULL結束符.源串strSource的字符會覆蓋目標串strDestination后面的結束符NULL. 在字符串的復制或添加過程中沒有溢出檢查, 所以要保證目標串空間足夠大. 不能處理源串與目標串重疊的情況. 函數返回strDestination值.char *strncat(char *strDestination, const char *strSource, size_t count);將源串strSource開始的count個字符添加到目標串strDest后. 源串strSource的字符會覆蓋目標串strDestination后面的結束符NULL. 如果count大于源串長度, 則會用源串的長度值替換count值. 得到的新串后面會自動加上NULL結束符. 與strcat函數一樣, 本函數不能處理源串與目標串重疊的情況. 函數返回strDestination值.char *strcpy(char *strDestination, const char *strSource);復制源串strSource到目標串strDestination所指定的位置, 包含NULL結束符. 不能處理源串與目標串重疊的情況.函數返回strDestination值.char *strncpy(char *strDestination, const char *strSource, size_t count);將源串strSource開始的count個字符復制到目標串strDestination所指定的位置. 如果count值小于或等于strSource串的長度, 不會自動添加NULL結束符目標串中, 而count大于strSource串的長度時, 則將strSource用NULL結束符填充補齊count個字符, 復制到目標串中. 不能處理源串與目標串重疊的情況.函數返回strDestination值.char *strset(char *string, int c); 將string串的所有字符設置為字符c, 遇到NULL結束符停止. 函數返回內容調整后的string指針. char *strnset(char *string, int c, size_t count);將string串開始count個字符設置為字符c, 如果count值大于string串的長度, 將用string的長度替換count值. 函數返回內容調整后的string指針.size_t strspn(const char *string, const char *strCharSet);查找任何一個不包含在strCharSet串中的字符 (字符串結束符NULL除外) 在string串中首次出現的位置序號. 返回一個整數值, 指定在string中全部由characters中的字符組成的子串的長度. 如果string以一個不包含在strCharSet中的字符開頭, 函數將返回0值.size_t strcspn(const char *string, const char *strCharSet);查找strCharSet串中任何一個字符在string串中首次出現的位置序號, 包含字符串結束符NULL. 返回一個整數值, 指定在string中全部由非characters中的字符組成的子串的長度. 如果string以一個包含在strCharSet中的字符開頭, 函數將返回0值.char *strspnp(const char *string, const char *strCharSet);查找任何一個不包含在strCharSet串中的字符 (字符串結束符NULL除外) 在string串中首次出現的位置指針. 返回一個指針, 指向非strCharSet中的字符在string中首次出現的位置.char *strpbrk(const char *string, const char *strCharSet);查找strCharSet串中任何一個字符在string串中首次出現的位置, 不包含字符串結束符NULL. 返回一個指針, 指向strCharSet中任一字符在string中首次出現的位置. 如果兩個字符串參數不含相同字符, 則返回NULL值. int strcmp(const char *string1, const char *string2);比較字符串string1和string2大小. 返回值< 0, 表示string1小于string2; 返回值為0, 表示string1等于string2; 返回值> 0, 表示string1大于string2. int stricmp(const char *string1, const char *string2);比較字符串string1和string2大小,和strcmp不同, 比較的是它們的小寫字母版本.返回值與strcmp相同. int strcmpi(const char *string1, const char *string2);等價于stricmp函數, 只是提供一個向后兼容的版本. int strncmp(const char *string1, const char *string2, size_t count);比較字符串string1和string2大小,只比較前面count個字符. 比較過程中, 任何一個字符串的長度小于count, 則count將被較短的字符串的長度取代. 此時如果兩串前面的字符都相等, 則較短的串要小.返回值< 0, 表示string1的子串小于string2的子串; 返回值為0, 表示string1的子串等于string2的子串; 返回值> 0, 表示string1的子串大于string2的子串. int strnicmp(const char *string1, const char *string2, size_t count);比較字符串string1和string2大小,只比較前面count個字符. 與strncmp不同的是, 比較的是它們的小寫字母版本. 返回值與strncmp相同.char *strtok(char *strToken, const char *strDelimit);在strToken 串中查找下一個標記, strDelimit字符集則指定了在當前查找調用中可能遇到的分界符. 返回一個指針, 指向在strToken中找到的下一個標記. 如果找不到標記, 就返回NULL值. 每次調用都會修改strToken內容, 用NULL字符替換遇到的每個分界符.
----------------------------------------------------------------------------
總結
以上是生活随笔為你收集整理的C 和 C++字符串详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CompletableFuture详解~
- 下一篇: 安卓逆向_8 --- Android 调