c 中字串擷取使用的方法

2022-03-19 21:46:45 字數 2073 閱讀 4654

string substring(int beginindex)

string substring(int beginindex, int endindex)

string.substring (int32) 子字串從指定的字元位置開始。

string.substring (int32, int32) 子字串從指定的字元位置開始且具有指定的長度。

舉例如下:

string s = "hello c# world!";

//s1為從s中擷取的位置為3的字元以後的字元子串,3表示子字串的起始字元位置

string s1=s.substring(3);

//s2為從s中擷取的位置為6的字元開始長度為2的字串,6表示子字元的起始字元位置,2表示子字元長度

string s2 = s.substring(6, 2);

結果如下:

lo c# world!

c#int indexof(string str) 返回第一次出現的指定子字串在此字串中的索引。

int indexof(string str, int fromindex) 從指定的索引處開始,返回第一次出現的指定子字串在此字串中的索引。

int lastindexof(string str) 返回在此字串中最右邊出現的指定子字串的索引。

int lastindexof(string str, int fromindex) 從指定的索引處開始向後搜尋,返回在此字串中最後一次出現的指定子字串的索引。

int length() 返回此字串的長度。

boolean startswith(string prefix) 測試此字串是否以指定的字首開始。

boolean startswith(string prefix, int toffset) 測試此字串是否以指定字首開始,該字首以指定索引開始。

例如:string str= "c:\\documents and settings\\administrator\\桌面\\new1.jpg"

str.substring(0,str.lastindexof("\\")+1)+"new"+str.substring(str.lastindexof("\\")+1,

str.lastindexof(".")-str.lastindexof("\\")-1)+str.substring(str.lastindexof("."),str.length-str.lastindexof(".")

str.lastindexof("\\")——得到最後乙個「\\」的索引值

str.substring(0,str.lastindexof("\\")+1)——得到 c:\\documents and settings\\administrator\\桌面\\

str.substring(str.lastindexof("\\")+1,str.lastindexof(".")-str.lastindexof("\\")-1) ——得到 new1

str.substring(str.lastindexof("."),str.length-str.lastindexof(".") ——得到 .jpg

string substring(int beginindex)

string substring(int beginindex, int endindex)

string.substring (int32) 子字串從指定的字元位置開始。

string.substring (int32, int32) 子字串從指定的字元位置開始且具有指定的長度。

舉例如下:

string s = "hello c# world!";

//s1為從s中擷取的位置為3的字元以後的字元子串,3表示子字串的起始字元位置

string s1=s.substring(3);

//s2為從s中擷取的位置為6的字元開始長度為2的字串,6表示子字元的起始字元位置,2表示子字元長度

string s2 = s.substring(6, 2);

結果如下:

lo c# world!

c#

c 中字串擷取使用的方法

string substring int beginindex string substring int beginindex,int endindex string.substring int32 子字串從指定的字元位置開始 string.substring int32,int32 子字串從指定的...

C 中擷取字串的方法

8種c 中擷取字串的方法 根據單個分隔字元用split擷取例如複製 如下 string st gt123 1 string sarray st.split 即可得到sarray 0 gt123 sarray 1 1 利用多個字元來分隔字串例如複製 如下 string str gtazb jiangj...

C 中字串的擷取

string str 123abcd456 int i 3 1 取字串的前i個字元 str str.substring 0,i or str str.remove i,str.length i 2 去掉字串的前i個字元 str str.remove 0,i or str str.substring ...