C 字串操作方法

2022-02-01 14:12:45 字數 1922 閱讀 5291

1.字串訪問

string str = "abcd";

str[0]      =>    "a"

str.length   => 4

2.拆分為字元陣列

string str ="abcd";

str.tochararray()    =>     ['a','b','c','d']

string str = "a,b,c,d";

str.split(',');          =>      [a,b,c,d]

3.擷取字串

string str = "abcd";

str.substring(1)     =>  "bcd"

str.substring(1,2)       =>   "bc"

4.匹配索引

string str = "abcabcd";

str.indexof('a')       =>  "0"

str.indexof("bcd")     =>   "4"

str.lastindexof('c')     =>  5

str.lastindexof("ab")    =>   3

str.indexof('e')      =>  "-1"

str.contains("abcd")   => true

5.大小寫轉換

string str = "abcd";

str.tolower()         =>   "abcd"

str.toupper()       =>    "abcd"

6.填充對其

string str = "abcd";

str.padleft(6,'_')      =>   "_abcd"

str.padright(6,"_")     =>   "abcd_"

7.截頭去尾

string str = "_ab_cd_";

str.trim("_")           =>      "ab_cd"

str.trimstart("_")        =>       "ab_cd_"

str.trimend("_")         =>    "_ab_cd"

8.插入和刪除

string str = "adef";

str.insert(1,"bc")         =>    "abcdef"

str.remove(1)           =>   "a"

str.remove(str.length-2,2) .remove(0,1)         =>   "d"

9.替換字元

string  s = "a_b_c_d"

str.replace("_","-")           =>   "a-b-c-d"

10. 分割字串

string str = "aa,bb,cc,dd";

char arr = str.split(",")        =>   ["aa","bb","cc","dd"]

11. 格式化

string.format("+ = ",1,2,1+2);

string.format("",datetime.now));

12.鏈結字串

string str = "a,b,c,d";

string  arr =  str.split(',')          =>        ["a","b","c","d"]     

string.concat(arr)            =>     "abcd"

string.join(",",arr)           =>      "a,b,c,d"

stringbuilder sb = new stringbuilder();

sb.tostring();

字串操作方法

indexof 返回查詢某乙個字串第一次出現的下標 定義字串 string.indexof 要查詢的字串 從哪一下標開始 返回第一次出現的下標 slice 擷取字串兩個引數第乙個是開始的下標,第二個是結束的下標,如果第乙個引數是負數就是倒數下標。str.slice 開始的位置,結束的位置 split...

C 字串操作方法總結

1 單個字元分隔用split擷取 string str gt123 1 string strarray str.split 輸出 sarray 0 gt123 sarray 1 1 2 利用多個字元來分隔字串 string str gtazb jiangjben 123 string strarra...

Python 字串操作方法

1.capitalize 把字串的第乙個字元改為大寫 2.casefold 把整個字串的所有字元改寫小寫 3.center width 將字串居中,並使用空格填充至長度width的新字串 4.count sub start end 返回sub在字串裡面出現的次數,start和end引數表示範圍,可選...