C 之string基本操作

2021-09-23 01:38:54 字數 2975 閱讀 5321

熟悉stl裡面的資料結構對我們做演算法題有非常大的幫助,博主在leetcode上做題就深感對stl的不熟練帶來的尷尬,大多停留在c語言的思想做題。而熟悉stl不但可以優化演算法,還可以裝逼。

string類簡化我們對字串的操作,想想c語言的字串的增刪改查,一不小心就bug了。string還封裝了專門用於寬字元的wstring,操作基本都一樣。

string有過載了非常多建構函式,這裡就只列出比較常用的:

#include#include#includeusing namespace std;

void main()

{ /*建構函式*/

string str1; //預設建構函式

string str2("abc"); //傳入string或者c_str

string str3(4, 'a'); //4個字元a構建成string

string str4(str2, 1); //從str2的位置1開始構造

string str5(str2.begin(), str2.end()); //從str2的迭代器開始構造

cout << str2 << endl << str3 << endl<< str4 << endl<+=操作符是string類之間的新增。

string str1("str1");

string str2("str2");

str1 += str2;

cout << str1 << endl;

string str1("str1");

cout << str1 << endl;

cout << str1 << endl;

string str2("str2");

cout << str2 << endl << str1 << endl;

string str1("str1");

str1.push_back('a');

cout << str1 << endl;

push_back()可以在string的後面新增乙個字元

string str1("str1");

str1.insert(0, "insert"); //從0開始插入引數字串

cout << str1 << endl;

str1.insert((string::size_type)0, 2, '0'); //在指定位置插入2個'0',用size_type強轉不會產生歧義

cout << str1 << endl;

str1.insert(str1.begin(), 3, 'b'); //迭代器指定位置後面插入3個'b'

cout << str1 << endl;

insert可以指定位置在目標string中插入。

string str1("string1");

str1.erase(0, 1); //刪除指定區間

cout << str1 << endl;

str1.erase(2); //指定刪除的起始位置,直至末尾

cout << str1 << endl;

string str1("string1");

str1.pop_back(); //從尾部彈出字元

cout << str1 << endl;

str1.clear();//清空字串,使字串為空
string str1("string1");

str1.replace(0, 2, "rep"); //把指定區間的字元替換成引數字串

cout << str1 << endl;

str1.replace(0, 2,"123",2);//把指定區間的字元替換成引數字串的前面2個

cout << str1 << endl;

str1.replace(0, 2, "456", 0, 3); //把指定區間的字元替換成引數字串指定的區間字元

cout << str1 << endl;

總結:replace( [ start, end ),"用於替換的字串",[ start, end ) ),即可以指定被替換的字串區間和用於替換的字串區間。

at:

cout << str1.at(1) << endl;//某個位置的字元
find:

string類提供的find成員函式可以查詢字元或者字串位置,凡是沒有找到的均返回string::npos,該值定義為-1。

string str1("string1string1");

cout << str1.find('i') << endl; //查詢某個字元位置

int idx=str1.find('2'); //不存在返回string::npos,-1

cout << idx << endl;

coutstring str1("string1string1");

string temp = str1.substr(0, 2); //指定區間的字串

cout << temp << endl;

string temp2 = str1.substr(1); //從指定位置開始切割至尾部

cout << temp2 << endl;

string str1("124");

cout << stoi(str1) << endl; //轉為整數

cout << stof(string("124.3")) << endl;//轉為浮點型

string str = to_string(124); //數字轉為字串

cout << str << endl;

str = to_string(13.4);

cout << str << endl;

C 基本操作(一) string

1,統計字串長度 int length 2,判斷是否為空 bool empty 3,字串的連線 4,字串的擷取 string substr int pos 0,int npos n 返回從pos開始的n個字元組成的字串 5,字串的查詢 只舉最簡單的例子 int find const string s...

C 之深淺拷貝及String類基本操作

今天我來介紹一下c 中的深淺拷貝問題。一。淺拷貝 1.定義 也稱位拷貝,編譯器只是將物件中的值採用基本型別值複製的方式拷貝過來,如果物件中管理資源,最後就會導致 多個物件共享同乙份資源,當乙個物件銷毀時就會將該資源釋放掉,而此時另一些物件不知道該資源已經被釋放,以為還有效,所以當繼續對資源進行操作時...

String類的基本操作

string類是表示字串的字串類,該類的介面與常規容器的介面基本相同,再新增了一些專門用來操作string的常規操作,string在底層實際是 basic string模板類的別名typedef basic stringstring 不能操作多位元組或者變長字元的序列。在使用string類時,必須包...