iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 18
3
Modern Web

C#與ASP.Net入門-我要成為工程師!!系列 第 18

Day18-C#-最常用的陣列!處理字串的一百種方法~(組合、切割、取代、擷取、尋找、修改)

  • 分享至 

  • xImage
  •  

好,首先,其實沒有一百種不要擔心XDDD浮誇一下浮誇一下XDDD

說到陣列,我們最常使用的陣列非字串莫屬了!!字串就是字元的陣列~

之後開始接觸ASP.NET網頁部分,可能常常需要對字串進行處理(組合、切割、取代、擷取、尋找、修改),先來介紹幾個字串常用的方法:

字串組合

  • 使用"+"號:常用
string a = "賀阿! ";
string b = "我!要!成!為!工!程!師!";

Console.WriteLine(a+b);
Console.ReadKey();

輸出結果:

https://ithelp.ithome.com.tw/upload/images/20190917/20120055daim9GgGGd.png

  • string format()常用→詳細介紹請看Day14這篇

  • String.Concat()
    String.Concat(字串a,字串b)

string a = "賀阿! ";
string b = "我!要!成!為!工!程!師!";
Console.WriteLine(String.Concat(a,b));
Console.ReadKey();

輸出結果:
https://ithelp.ithome.com.tw/upload/images/20190917/20120055PLkNh7FuR0.png

  • String.Join()

String.Join(String(用來連結的字串), String[](字串陣列,被連結的字串們))

string[] array = { "賀阿!", "我!要!成!為!工!程!師!" };
Console.WriteLine(String.Join("**********",array));//用*連接兩字串
Console.ReadKey();

輸出結果:
https://ithelp.ithome.com.tw/upload/images/20190917/20120055ffppzoX6qU.png

  • StringBuilder.Append()

將字串a建立一個StringBuilder物件,並使用Append("要加入的字串")方法將字串連接
注意StringBuilder物件跟字串不一樣喔

StringBuilder stringBuilder = new StringBuilder("賀阿!");
stringBuilder.Append("我!要!成!為!工!程!師!");
Console.WriteLine(stringBuilder);
Console.ReadKey();

輸出結果:
https://ithelp.ithome.com.tw/upload/images/20190918/20120055RXV4RBH0R9.png


字串切割

使用 Split() 這個方法,用來分割的字元不會存在在分割結果。常用

  • 使用單個字元切割
    Split('要用來切割的字元')
string b = "我!要!成!為!工!程!師!";
string[] sArray = b.Split('!');//以字元!作為分隔符號
foreach (var item in sArray)
Console.WriteLine(item);
Console.ReadKey();

輸出結果:
https://ithelp.ithome.com.tw/upload/images/20190918/20120055JoqxcxLZ5v.png

  • 使用多個字元切割
    Split(char[]{'分隔字元','分隔字元'})
string b = "我!要!成!為!工~程~師!";
string[] sArray = b.Split(new char[2] {'!','~'});//分別以!還有~y作為分隔符號
foreach (var item in sArray)      
Console.WriteLine(item);
Console.ReadKey();

輸出結果:
https://ithelp.ithome.com.tw/upload/images/20190918/201200554cTT44AEjo.png

  • 使用多個字串分割

Split(用來切割的字串陣列String[], StringSplitOptions)

string b = "我!要!成!為!工~程~師!";
string[] sArray = b.Split(new string[] {"成","程"}, StringSplitOptions.RemoveEmptyEntries);
//RemoveEmptyEntries代表不回傳空字串的元素
foreach (var item in sArray)        
Console.WriteLine(item);
Console.ReadKey();

輸出結果:
https://ithelp.ithome.com.tw/upload/images/20190918/20120055o77i0PCyF8.png

Regex.Split(要切割的字串,"要用來切割的字串")

string b = "我!要!成!為!工!程!師!";
string[] sArray = Regex.Split(b,"為!");
foreach (var item in sArray)
Console.WriteLine(item);
Console.ReadKey();

輸出結果:
https://ithelp.ithome.com.tw/upload/images/20190918/20120055SLqePt6Nvs.png


字串取代

Replace(被取代的字元/字串,新的字元/字串)常用

string b = "我!要!成!為!工~程~師!";
string c =b.Replace("我", "Cynthia");//用Cynthia把我取代掉
Console.WriteLine(c);
Console.ReadKey();

輸出結果:
https://ithelp.ithome.com.tw/upload/images/20190918/20120055RqwfZT0kc2.png


字串擷取

複習一下index指的位置
https://ithelp.ithome.com.tw/upload/images/20190918/2012005585Nv9Ch2JO.png

  • Substring(抓取起始字串index):這個會從某個字串開始一直到最後常用
    Substring(Int32)

    string b = "我要成為工程師";
    string c = b.Substring(3);//從index=3開始抓,所以是從"為"開始
    Console.WriteLine(c);
    Console.ReadKey();
    

    輸出結果:
    https://ithelp.ithome.com.tw/upload/images/20190918/20120055uNhFVlinah.png

  • Substring(抓取起始字串index(int),抓的字串長度(int)):指定抓取起點與抓取長度常用
    Substring(Int32,Int32)

    string b = "我要成為工程師";
    string c = b.Substring(3,2);//從index=3開始抓,往後抓2個
    Console.WriteLine(c);
    Console.ReadKey();
    

    輸出結果:

    https://ithelp.ithome.com.tw/upload/images/20190918/20120055l1VGxIgIuh.png


字串尋找

  • 概念一:直接搜尋文字

    • String.Contains(string要查的字串):看括號內的值是否在字串內,傳回值為布林值boolean(T/F)常用
    string b = "我要成為工程師";
    bool c = b.Contains("我");//看"我"是否存在b字串裡
    Console.WriteLine(c);
    Console.ReadKey();
    

    輸出結果:
    https://ithelp.ithome.com.tw/upload/images/20190918/20120055ezr5bhc4hf.png

    • String.StartsWith(string要查的字串):看字串是否以括號內的值開頭,傳回值為布林值boolean(T/F)
    • String.EndsWith(string要查的字串):看字串是否以括號內的值結尾,傳回值為布林值boolean(T/F)
    string b = "我要成為工程師";
    bool c = b.StartsWith("我");
    bool d = b.EndsWith("我");
    Console.WriteLine(c);
    Console.WriteLine(d);
    Console.ReadKey();
    

    輸出結果:
    https://ithelp.ithome.com.tw/upload/images/20190918/20120055CwAU27fZp6.png

  • 概念二:找到字串的位置

    • IndexOf("要尋找的內容"):找到這個字元或字串第一次出現的索引位置,如果找不到會回傳-1。常用
    • LastIndexOf("要找的內容"):找到這個字元或字串最後一次出現的索引位置,如果找不到會回傳-1

    因為第一個位置是0,所以if(IndexOf()>-1)表示存在

     string b = "我要成為工程師我";
     int c = b.IndexOf("我");
     int d = b.LastIndexOf("我");
     Console.WriteLine(c);
     Console.WriteLine(d);
     Console.ReadKey();
    

    輸出結果:
    https://ithelp.ithome.com.tw/upload/images/20190918/201200559eRpS4iRgy.png

  • 使用正則運算式RegularExpressions的IsMatch()除非使用RegularExpressions,不然不建議這樣寫
    IsMatch(被搜尋的字串,要比對的字串)

    string b = "我要成為工程師我";
    bool c = Regex.IsMatch(b, "我");//看"我"在不在b字串裡
    Console.WriteLine(c);
    Console.ReadKey();
    

字串修改

  • 移除開頭或結尾的字元/空白

    • String.Trim():移除開頭和結尾空白。常用
    • String.Trim(Char[]):移除開頭和結尾的指定字元。
    • String.TrimStart(Char[]):移除開頭的指定字元。
    • String.TrimEnd(Char[]):移除結尾的指定字元。
    string b = "    我要成為工程師我    ";
    string c = "我要成為工程師!";
    Console.WriteLine(b.Trim());//移除前後空白
    Console.WriteLine(b.TrimStart());//移除前面空白
    Console.WriteLine(b.TrimEnd());//移除後面空白
    Console.WriteLine(c.Trim('!'));//移除前後!
    

    輸出結果:
    https://ithelp.ithome.com.tw/upload/images/20190918/20120055G3k4s7W2Qr.png

  • 移除文字

    • Remove("從第幾個開始移除"):Remove(Int)
    • Remove("從第幾個開始移除",總共移除幾個):Remove(Int,Int)
     string c = "我要成為工程師!";
     Console.WriteLine(c.Remove(2));
     Console.WriteLine(c.Remove(2,2));
     Console.ReadKey();
    

    輸出結果:
    https://ithelp.ithome.com.tw/upload/images/20190918/20120055bRILnmMV0r.png

  • 插入字串
    String.Insert("從第幾個index插入", "要插入的字串"):String.Insert(Int32, String)

    string c = "我要成為工程師!";
    Console.WriteLine(c.Insert(1,"!Cynthia"));
    Console.ReadKey();
    

輸出結果:
https://ithelp.ithome.com.tw/upload/images/20190918/20120055CVvRs8mFNB.png


上一篇
Day17-C#陣列Array、不規則陣列。神啊~我找到處理多筆資料的好朋友了!
下一篇
Day19-C#-正規表達式Regular Expression-你知道身分證字號的秘密嗎?
系列文
C#與ASP.Net入門-我要成為工程師!!31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
小朱
iT邦新手 4 級 ‧ 2019-09-19 14:23:42

如果不是用正規表達式的規則字串的話,一般只會用 string.Split()、string.Contains() 或 string.IndexOf() 而已,不會去用 Regex.IsMatch() 或是 Regex.Split(),因為命名空間不同,而且容易使別人搞混 (尤其是初學者)。

另外,StringBuilder 和 string 雖然很像但是不同的東西喔。

如果不是用正規表達式的規則字串的話,一般只會用 string.Split()、string.Contains() 或 string.IndexOf() 而已,不會去用 Regex.IsMatch() 或是 Regex.Split(),因為命名空間不同,而且容易使別人搞混 (尤其是初學者)。

我雖然知道他們不同,但我這初學者顯然寫了讓人容易搞混的東西XD我立馬備註一下XD也提醒自己別亂用XD

另外,StringBuilder 和 string 雖然很像但是不同的東西喔。
好的!感謝大大提醒!看來我這樣寫會讓人誤會,這我也在內文備註一下XD

謝謝你~

0
Ottis
iT邦新手 5 級 ‧ 2020-05-13 20:28:04

感謝分享這麼仔細的教學,最近剛開始接觸C#,偶然間搜尋到妳的文章,感覺真的獲益良多~!

我要留言

立即登入留言