C 的string類常用函式

2021-10-13 05:03:20 字數 1969 閱讀 2574

c++的string類常用函式

s.assign() // 對字串賦以新值

string s = "liulan";

s.assign("niupi");

swap() // 交換兩個字串的內容

string s1 = "liulan";

string s2 = "gmy";

cout << s1 << " " << s2 << endl;

s2.swap(s1);

cout << s1 << " " << s2 << endl;

return 0;

string s1 = "liulan";

string s2 = "gmy";

string s = s1+s2;

cout << s << endl;

// s = "liulangmy"

s.insert() // 插入字元

string s = "liulan";

s.insert(0,"gaomy");

// s = "gmyliulan"

s.erase() // 刪除字元

string s = "liulan";

s.erase(0,1);

//s = "iulan"

s.clear() // 刪除全部字元

s.replace() // 替換字元

string s = " liulan";

s.replace(0,1,"gmy");

cout << s << endl;

+ // 串聯字串

==,!=,<,<=,>,>=,compare() // 比較字串

size(),length() // 返回字元數量

max_size() // 返回字元的可能最大個數

s.empty() // 判斷字串是否為空

s.capacity() // 返回重新分配之前的字元容量

reserve() // 保留一定量記憶體以容納一定數量的字元

[ ], at() // 訪問單一字元

getline() // 從stream讀取某值

<< // 將謀值寫入stream

#include#include#include#includeusing namespace std;

int main()

copy() // 將string的某值賦值為乙個c_string

string s = 「123」;

char* c =new char[10];

s.copy(c,2,0);

cout << s << endl;

cout << c << endl;

c_str() // 返回乙個指向正規c字串(c_string)的指標 內容與本string串相同 有』\0』

法一:

string s = " liulan";

const char* c;

c = s.c_str();

//改變s時,c也會改變

法二:

#includechar* c = new char[10];

strcpy(c,s.c_str());

法二更安全

data() // 將內容以字元陣列形式返回 無』\0』

s.substr() // 返回某個子字串

string s = " liulan";

string s1 = s.substr(0,3);

begin() end() // 提供類似stl的迭代器支援

rbegin() rend() // 逆向迭代器

get_allocator() // 返回配置器

c 中常用的String類

一.字串常用方法 1.indexof 如果找到字串出現的位置則為索引位置,否則返回 1,索引從0開始 2.string substring int startindex int length 從開始位置startindex,擷取到結束位置 擷取長度length 3.trim 清除前後兩端空格 4.t...

string類常用函式的應用大全

string類的實操.cpp 此檔案包含 main 函式。程式執行將在此處開始並結束。include include using namespace std int main cout endl 字串的替換 str5.replace str5.begin str5.end str1.c str 5 ...

常用類 String類

string類概述 字串是由多個字元組成的一串資料 字串行 字串可以看成是字元陣列 構造方法 public string public string byte bytes public string byte bytes,int offset,int length public string cha...