詳解C++字串常用操作函式(查詢、插入、擷取、刪除等)
阿新 • • 發佈:2021-01-13
1. 字串查詢函式
1.1 find 函式
原型為:unsigned int find(const basic_string &str) const;
作用:查詢並返回str在本串中第一次出現的位置,位置從0開始
例子如下:
#include <iostream> using namespace std; int main() { string str = "i love china. china love me"; string find_str = "love"; cout << str.find(find_str); // 2 return 0; }
2. 字串插入函式
2.1 append
- 函式原型為:
string append(const char* s) ;
- 作用:將字串s新增到本串尾,改變本串
- 例子如下:
#include <iostream> using namespace std; int main() { string str = "i love china. "; char append_str[] = "china love me"; cout << str.append(append_str) << endl; // i love china. china love me cout << str << endl; // i love china. china love me return 0; }
2.2 insert
- 函式原型為:
string & insert(unsigned int p0,const char * s);
- 作用:將s所指向的字串插入在本串中位置p0之前,改變本串
- 例子如下:
#include <iostream> using namespace std; int main() { string str = "i love . china love me"; char insert_str[] = "china"; cout << str.insert(7,insert_str) << endl; // i love china. china love me cout << str << endl; // i love china. china love me return 0; }
3. 字串擷取函式
3.1 substr
- 函式原型為:
string substr(unsigned int pos,unsigned int n) const;
- 作用:取子串,取本串中位置pos開始的n個字元,構成新的string類物件作為返回值
- 例子如下:
#include <iostream> using namespace std; int main() { string str = "i love china. china love me"; cout << str.substr(2,22) << endl; // love china. china love return 0; }
4. 字串刪除函式
4.1 函式
- 原型1為:
string & erase(unsigned int pos);
- 作用1:刪除本串pos位置及之後的所有字元,改變本串
- 函式原型2為:
string & erase(unsigned int pos, unsigned int n);
- 作用2:刪除本串pos位置及之後的共n個字元,改變本串
- 例子如下:
#include <iostream> using namespace std; int main() { string str1 = "i love china. china love me"; cout << str1.erase(12) << endl; // i love china cout << str1 << endl; // i love china string str2 = "i love china. china love me"; cout << str2.erase(7,18) << endl; // i love me cout << str2 << endl; // i love me return 0; }
到此這篇關於C++字串常用操作函式(查詢、插入、擷取、刪除等)的文章就介紹到這了,更多相關C++字串操作函式內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!