C 字串操作

2021-08-26 18:18:16 字數 3467 閱讀 5002

最近做專案的時候在解析一串非常複雜的字串時發現自己根本沒記住幾種相關字串的操作,今天剛好有時間就整理一下常用的字串操作,以後也方便。

string oldstring = "123|456"; 

1.trim清空

string newstring = oldstring.trim(); //123|456將字串兩邊的空格清空

string newstring = oldstring.trim(new char ); //3|456將字串開始與末尾的字元1和2清空

string newstring = oldstring.trimstart(); //123|456將字串結尾的空格清空

string newstring = oldstring.trimstart(new char ); //3|456將字串開始的字元1和2清空

string newstring = oldstring.trimend(); //123|456將字串結尾的空格清空

string newstring = oldstring.trimend(new char ); //123|4將字串末尾的字元1和2清空

2.equals是否相等

bool b = oldstring.equals("1"); //false判斷字串與"1"是否相等

3.contains是否存在

bool b= oldstring.contains("1"); //true判斷字串是否存在"1"

4.replace替換

string newstring = oldstring.replace("123", "456"); //456|456把oldstring裡的"123", 換成"456"

string newstring = oldstring.replace("|", ""); //123456將"|"字元替換為"",即將「|「刪除

5.remove刪除

string newstring = oldstring.remove(3); //123刪除3位置以後的字元

string newstring = oldstring.remove(0,2); //3|456刪除0位置以後的2個字元 

6.substring提取

string newstring = oldstring.substring(3); //|456提取3位置以後的所有字元

string newstring = oldstring.substring(3,4); //|4提取介於3-4指定下標之間的字元

7.split拆分

string split= oldstring.split('|'); //split[1]=456按照|進行全部拆分

8.concat連線

string newstring= string.concat(split); //123456連線拆分的split

string newstring= string.join("|", split); //123|456間隔|連線拆分的split

9.insert插入

string newstring = oldstring.insert(3,"7"); //1237|456在3位置之前插入字元7

10.indexof存在索引

int num = oldstring.indexof("|"); //3輸出第乙個匹配的字元位置索引,不存在返回-1

int num = oldstring.lastindexof("|"); //3輸出最後一次出現匹配的字元位置索引

11.padleft/padright填充對齊

string newstring = oldstring.padleft(9, '7'); //77123|456從開始以7補齊字串的長度為9

string newstring = oldstring.padright(9, '7'); //123|45677從結尾以7補齊字串的長度為9

12.tolower/toupper字母大小寫

string newstring = oldstring.tolower(); //123|456轉化為小寫字母

string newstring = oldstring.toupper(); //123|456轉化為大寫字母

bool b = char.isupper(oldstring, 3); //false判斷字串中的第3個字元是否是大寫

13.endswith/startswith是否對應

bool b = oldstring.endswith("1"); //false判斷字串是否以1結尾

bool b = oldstring.startswith("1"); //true判斷字串是否以1開始

14.字串與utf-8位元組陣列

byte b = encoding.utf8.getbytes(oldstring); //字串轉換成utf-8位元組陣列

string newstring = encoding.utf8.getstring(位元組陣列, 0, 陣列length); //utf-8位元組陣列轉換成字串

15.json與物件

string obj = jsonconvert.serializeobject(te); te是要序列化的物件;obj是物件序列化後的字串

testentity te = jsonconvert.deserializeobject(obj); //testentity是目標型別,obj是經過json序列化的物件,字串形式

在面對複雜的字串解析時,靈活的混合使用各種字串方法能讓你事半功倍。

geniy

c 字串操作

獲得漢字的區位碼 bytearray newbyte 2 求字串長度 求字串長度 int len string inputstring 檢測含有中文字串的實際長度 str為要檢測的字串 asciiencoding n new asciiencoding byte b n.getbytes str i...

C 字串操作

1.根據單個分隔字元用split擷取 例如複製 如下 string st gt123 1 string sarray st.split 即可得到sarray 0 gt123 sarray 1 1 2.利用多個字元來分隔字串 例如複製 如下 string str gtazb jiangjben 123...

C字串操作

c字串操作 注 文中的幾個大小寫不敏感比較函式,原文用的是stricmp等,後來發現linux的std庫沒有,改為strcasecmp系列。函式名 strcpy 功 能 拷貝乙個字串到另乙個字串 用 法 char strcpy char destin,char source 程式例 i nclude...