C++字符串详解(三) 字符串的增删改
生活随笔
收集整理的這篇文章主要介紹了
C++字符串详解(三) 字符串的增删改
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一. 插入字符串
insert() 函數(shù)可以在 string 字符串中指定的位置插入另一個字符串,它的一種原型為:
pos 表示要插入的位置,也就是下標(biāo);str 表示要插入的字符串,它可以是 string 字符串,也可以是C風(fēng)格的字符串。
#include <iostream> #include <string> using namespace std; int main(){string s1, s2, s3;s1 = s2 = "1234567890";s3 = "aaa";s1.insert(5, s3);cout<< s1 <<endl;s2.insert(5, "bbb");cout<< s2 <<endl;return 0; } 12345aaa67890 12345bbb67890二. 刪除字符串
erase() 函數(shù)可以刪除 string 中的一個子字符串。它的一種原型為:
string& erase (size_t pos = 0, size_t len = npos);
pos 表示要刪除的子字符串的起始下標(biāo),len 表示要刪除子字符串的長度。如果不指明 len 的話,那么直接刪除從 pos 到字符串結(jié)束處的所有字符(此時 len = str.length - pos)。
請看下面的代碼:
#include <iostream> #include <string> using namespace std; int main(){string s1, s2, s3;s1 = s2 = s3 = "1234567890";s2.erase(5);s3.erase(5, 3);cout<< s1 <<endl;cout<< s2 <<endl;cout<< s3 <<endl;return 0; } 1234567890 12345 1234590三. 提取子字符串
substr() 函數(shù)用于從 string 字符串中提取子字符串,它的原型為:
string substr (size_t pos = 0, size_t len = npos) const;
pos 為要提取的子字符串的起始下標(biāo),len 為要提取的子字符串的長度。
請看下面的代碼:
#include <iostream> #include <string> using namespace std; int main(){string s1 = "first second third";string s2;s2 = s1.substr(6, 6);cout<< s1 <<endl;cout<< s2 <<endl;return 0; } first second third second系統(tǒng)對 substr() 參數(shù)的處理和 erase() 類似:
- 如果 pos 越界,會拋出異常;
-如果 len 越界,會提取從 pos 到字符串結(jié)尾處的所有字符。
總結(jié)
以上是生活随笔為你收集整理的C++字符串详解(三) 字符串的增删改的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++字符串详解(二)访问与拼接
- 下一篇: 爬百度图片