c++ string的erase刪除方法
之前不是很清楚c++中string如何刪除元素,現(xiàn)在記錄一下。
(參考自 c++ primer plus 第六版 模版類 string)
string中提供的成員函數(shù)可以用來刪除字符串中的字符,這里主要介紹erase方法
erase方法原型
1. basic_string & erase(size_type pos=0, size_type n=npos);
即從給定起始位置pos處開始刪除, 要刪除字符的長度為n, 返回值修改后的string對象引用
示例[1]
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "hello c++! +++";
// 從位置pos=10處開始刪除,直到結(jié)尾
// 即: " +++"
str.erase(10);
cout << '-' << str << '-' << endl;
// 從位置pos=6處開始,刪除4個字符
// 即: "c++!"
str.erase(6, 4);
cout << '-' << str << '-' << endl;
return 0;
}
輸出

2. iterator erase(const_iterator position)
刪除迭代器位置處的單個字符, 并返回下個元素的迭代器
3. iterator erase(const_iterator first, const_iterator last)
刪除迭代器[first, last)區(qū)間的所有字符,返回一個指向被刪除的最后一個元素的下一個字符的迭代器.
示例[2,3]:
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "hello c++! +++";
// 刪除"+++"前的一個空格
str.erase(str.begin()+10);
cout << '-' << str << '-' << endl;
// 刪除"+++"
str.erase(str.begin() + 10, str.end());
cout << '-' << str << '-' << endl;
return 0;
}
輸出

補充
除了erase方法用于刪除string中的元素, void pop_back();方法也可以用來刪除元素, 但是只能刪除string的最后一個元素
查找方法
在使用erase刪除函數(shù)的時候,經(jīng)常會和查找函數(shù)一起使用
*find*(**)系列方法參數(shù)可以是char 或者 string 類型, 為待查找的目標(biāo), 返回值為 size_type;當(dāng) 查找不到目標(biāo)時,返回值為 npos, 可以這樣判斷
string longer("That's a funny hat.");
//size_type loc1 = longer.find("hat"); // 存在
size_type loc1 = longer.find("hello"); //不存在
if (loc1 == string::npos)
cout<< "not found" <<endl;
以上這篇c++ string的erase刪除方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
c/c++ 標(biāo)準庫 bind 函數(shù)詳解
bind是一組用于函數(shù)綁定的模板。在對某個函數(shù)進行綁定時,可以指定部分參數(shù)或全部參數(shù),也可以不指定任何參數(shù),還可以調(diào)整各個參數(shù)間的順序。這篇文章主要介紹了c/c++ 標(biāo)準庫 bind 函數(shù) ,需要的朋友可以參考下2018-09-09
詳解Matlab繪制3D玫瑰花的方法(內(nèi)附旋轉(zhuǎn)版本)
這篇文章主要為大家介紹了如何利用Matlab繪制3D版的玫瑰花以及旋轉(zhuǎn)版的3D玫瑰花,文中的示例代碼講解詳細,感興趣的小伙伴可以動手試一試2022-03-03
Linux?C/C++?timeout命令實現(xiàn)運行具有時間限制功能
inux?timeout命令的一個屬性是時間限制。可以為任何命令設(shè)置時間限制。如果時間到期,命令將停止執(zhí)行,這篇文章主要介紹了Linux?C/C++?timeout命令實現(xiàn)(運行具有時間限制),需要的朋友可以參考下2023-02-02

