c 關於string常用函式

2021-10-08 11:44:42 字數 1950 閱讀 3795

c++的string有兩種賦值方式

//兩種賦值方式 

string str1=

"string1"

; string str2

("string2");

cout<

" "<

輸出

子字串的查詢

方法一:呼叫find方法

//子字串的查詢

string strall=

"abcdefgbcd"

; string strzi

("bc");

//返回第一次出現索引 沒有返回-1

int i=strall.

find

("defg");

//從後往前找

int j=strall.

rfind

("bd");

cout<

" "<

char a=

"nihao"

;char b=

"hao"

;char

*p=strstr

(a,b);if

(p!=

null

)

擷取字串

擷取字串 substr(size_t pos=0,size_t len=npos),第乙個引數為擷取的位置,第二個引數為擷取的長度 ,原字串不改變

string cut1=strall.

substr(2

);string cut2=strall.

substr(2

,4);

//超過了字串的長度仍會輸出

string cut3=strall.

substr(2

,6);

cout<

" "<

" "<

" "<

輸出:

字串插入

改變了原有字串 ,第乙個引數要插入的位置,第二個引數要插入的字串

string s1=

"helld"

; string s2=

"o worl"

; s1.

insert(4

,s2)

; cout<

輸出:

第三個引數為s4的起始位置,第四個引數為結束位置 左開右閉

string s3=

"china"

; string s4=

"gggood"

; s3.

insert(5

,s4,2,

6); cout<

在第乙個引數位置之前插入第二個引數個數的第三個引數字元

string s5=

"gd"

;char ch=

'o';

s5.insert(1

,2,ch)

; cout<

刪除字串

刪除引數後的所有字元(包括引數所在位置)

string s6=

"abcdefg"

; s6.

erase(3

);cout<

刪除引數位置後n個字元

string s7=

"abcd"

; s7.

erase(2

,1);

cout<

Java中關於String的常用函式

一 構造方法 public string 建立string物件 public string byte bytes 把位元組陣列轉成字串。public string byte bytes,int index,int length 把位元組陣列中的一部分轉成字串 public string char v...

string 常用函式

string的一常用函式,待補充 string擷取 替換 查詢子串函式 擷取子串 s.substr pos,n 擷取s中從pos開始 包括0 的n個字元的子串,並返回 s.substr pos 擷取s中從從pos開始 包括0 到末尾的所有字元的子串,並返回 替換子串 s.replace pos,n,...

C 中String常用函式總結

1.string類提取子串函式 s.substr 返回s的全部內容 s.substr 11 從索引11往後的子串 s.substr 5,6 從索引5開始6個字元 2.string類的查詢函式 查詢成功時返回所在位置 第乙個字元索引 失敗返回string npos的值 int find char c,...