C# 新手教學(5) 字串處理

來自 | 8 月 3, 2024 | 程式 | 0 條留言

處理字串也是C#常做的事情,此文會介紹stringStriinBuilter常見用法

String還是string

根據微軟官方說明,兩個是相同的東西,但建議使用string就好,我個人也是習慣使用string,然後如果公司這部分有規定就照公司規定就好。

宣告string

字串要用 包起來。

string name; //沒初始值,內容會是null
string company = "dream mall"; //有初始值,前後要使用雙引號包
string emptyString = string.Empty; //定義一個空字串

字串連接

用 字串+字串 串接了

string love = "我愛"+ "海綿寶寶";
Console.WriteLine(love); //我愛海綿寶寶

驗證字串長度string.Length

雖然string.Count也可以用,不過Count效率比較糟糕,它是轉成 IEnumerable在進行Count運算。

注意,有些程式語言的字數計算會把中文字算成兩個字,全型逗號也算兩個字,不過C#在這方面處理比較好不會造成這個問題。

string name = "John愛吃棒棒糖";
Console.WriteLine(name.Length); // 9

注意,如果字串沒有設定內容,程式碼會拋出錯誤。

string name;
Console.WriteLine(name.Length); // 執行時這邊會拋出錯誤 Error

字串串接 string.Join()

這個功能非常常使用,尤其資料從List或Datatable讀出來的時候,要將輸出資料串接起來可以直接使用string.Join。

string.Join("分隔", 來源字串陣列 )

範例 使用「、」串接字串

string[] 好人卡 = { "恩恩", "哈哈", "去洗澡" };
Console.WriteLine(string.Join("、", 好人卡));//輸出:恩恩、哈哈、去洗澡
Console.ReadKey();

取代字串string.Replace()

字串變數.Replace("舊字串","新字串")

string orgingString = "Hello, world! Hello, everyone!";
string newString = originalString.Replace("Hello", "Hi");

Console.WriteLine("原始字串為: " + orgingString);
Console.WriteLine("取代後新字串: " + newString);

字串取代範例

驗證空字串string.IsNullOrEmpty()

Console.WriteLine(string.IsNullOrEmpty("") ? "true" : "false");  //true
Console.WriteLine(string.IsNullOrEmpty(null) ? "true" : "false"); //true
Console.WriteLine(string.IsNullOrEmpty(string.Empty) ? "true" : "false"); //true
Console.WriteLine(string.IsNullOrEmpty(" ") ? "true" : "false"); //半形空白 false

這個在使用者輸入空白 的狀況下這個驗證會為false。

驗證空白字串與空格string.IsNullOrWhiteSpace

Console.WriteLine(string.IsNullOrWhiteSpace("") ? "true" : "false");  //true
Console.WriteLine(string.IsNullOrWhiteSpace(null) ? "true" : "false"); //true
Console.WriteLine(string.IsNullOrWhiteSpace(string.Empty) ? "true" : "false"); //true
Console.WriteLine(string.IsNullOrWhiteSpace(" ") ? "true" : "false"); //半形空白 true
Console.WriteLine(string.IsNullOrWhiteSpace(" ") ? "true" : "false");//全型空白 true
Console.WriteLine(string.IsNullOrWhiteSpace("     ") ? "true" : "false");//很多個全型空白
Console.WriteLine(string.IsNullOrWhiteSpace("\r\n") ? "true" : "false");//換行
Console.WriteLine(string.IsNullOrWhiteSpace("\t") ? "true" : "false");//tab
Console.WriteLine(string.IsNullOrWhiteSpace("\t\n") ? "true" : "false");//tab + 換行

即使使用者只輸入空白,仍會被判定為true,這個函數比較常用在驗證使用者是否有輸入值

string input ;
//一些讀取使用輸入的程式
//...
//驗證
if(string.IsNullOrWhiteSpace(input))
{
   //設定錯誤訊息&離開程式
}

範例資料庫查詢組裝

//假如使用者有輸入關鍵字的話
if(!string.IsNullOrWhiteSpace(keyword)){
   //加入關鍵字查詢
   query = query.Where(n.Name.Contains(keyword));
}

這個很常用在製作網站時,讓使用者可以做進階查詢使用。

分割字串 string.Split()

官方說明 String.Split Method (System) | Microsoft Learn

分割字串,如果是寫網頁,這個很常用在處理複選的項目。
例如開放時間:


實際上存在資料庫有時會存成0,1,2,3,6 ,這時處理時就會使用字串分割處理值。

//字串.Split('分割字元');

opentime = "0,1,2,3,6";
string days[] = opentime.Split(',');
string s = "安安 幾歲 住哪?";

string[] 問安 = s.Split(' ');

foreach (var item in 問安)
{
    Console.WriteLine($"切割後: {item}");
}
//輸出如下
//安安
//幾歲
//住哪?

進階用法,多個分割字元

//字串.Split('分割字元1','分割字元2','分割字元3'...);

string s = "你不是一無所有,你還有病。條條大路通羅馬,但有些人一出生就在羅馬。";

string[] 雞湯 = s.Split(',', '。');
foreach (var item in 雞湯)
    Console.WriteLine($"{item}");
//你不是一無所有
//你還有病
//條條大路通羅馬
//但有些人一出生就在羅馬

輸出畫面

C#字串分割進階用法輸出

擷取部分字串string.substring()

官方說明 String.Substring Method (System) | Microsoft Learn

//用法:字串.Substring(開始位置,長度)
//注意,第一個字位置從0開始
string sea = "海綿寶寶與派大星";

//假如我要擷取「海綿寶寶」
string name = sea.Substring(0,4);

//假如我要擷取最後三個字
//最後一個字的位置為 sea.Length - 1
//倒數三個字的位置為最後一個字的位置-2
//(sea.Length -3)
string name2 = sea.Substring(sea.Length - 3 ,3);

去除前後空白 string.Trim()

官方說明 String.Trim Method (System) | Microsoft Learn

這功能很常用在網頁上避免使用者輸入多於空白

範例:去除關鍵字搜尋的空白

//假如使用者有輸入關鍵字的話
if(!string.IsNullOrWhiteSpace(keyword)){
  //去除前後空白
  keyword = keyword.Trim();

  //加入關鍵字查詢條件(下一行語法之後學到Linq再教)
  query = query.Where(n=>n.Name.Contains(keyword));
}

去除後面空白string.TrimEnd()

官方說明 String.TrimEnd Method (System) | Microsoft Learn

很少用,筆者暫時想不到實際案例

去除前空白string.TrimStart()

官方說明 String.TrimStart Method (System) | Microsoft Learn

很少用,筆者暫時想不到實際案例

搜尋字串 string.IndexOf()

微軟官網連結

可以找到指定的字元或字串在什麼位置

string text = "[email protected]";
string searchString = "@";

int index = text.IndexOf(searchString);
if (index != -1)
{
    Console.WriteLine($"找到'{searchString}' 在位置 {index}.");
}
else
{
    Console.WriteLine($"找不到'{searchString}'");
}
//注:如果只是要驗證字串內字元,有更好的辦法

驗證字串是否包含特定字詞 string.Contains

string email = "[email protected]";
string searchString = "Welcome";

if (text.Contains(searchString))
{
  Console.WriteLine($"'{searchString}' is found in the text.");
}
else
{
  Console.WriteLine($"'{searchString}' is not found in the text.");
}

全部轉小寫 string.ToUpper() 全部轉大寫string.ToLower()

微軟官方說明:ToUpper連結 ToLower連結

有些情況我們會需要將使用者輸入的資料全部改為小寫或大寫,就會派上用場了。例如發票號碼需要全部大寫、帳號名稱全部轉小寫。

範例:發票號碼處理

//發票號碼的例子
string invoiceNumber ;

//假設使用者輸入了發票號碼
invoiceNumber = "yh12345678";
Console.WriteLine($"使用者輸入資料為:'{invoiceNumber}'");

//轉大寫
invoiceNumber = invoiceNumber.ToUpper();
Console.WriteLine($"修正後資料為:'{invoiceNumber}'");

範例:帳號

//帳號的例子
string account;

//假設使用者輸入帳號
account = "testUser";
if(!string.IsNullOrWhiteSpace(account)){

  account = account.ToLower();

  //檢查帳號是否正確
  if(account == "testuser")
  {
    //帳號存在
    Console.WriteLine($"登入成功");
  }else{
    //帳號不存在
    Console.WriteLine($"登入失敗");
  }
}else{
  //使用者輸入空白
  Console.WriteLine($"登入失敗");
}

在特定位置插入字串 string.Insert(位置,插入內容)

微軟官方說明:連結

這個功能其實不常用,目前想不到實用的案例。

//這是官網的例子
//有個字串aaabbb 要在中間加入空白成為aaa bbb。
string original = "aaabbb";
Console.WriteLine("原始的字串: '{0}'", original);

string modified = original.Insert(3, " ");
Console.WriteLine("修改後字串: '{0}'", modified);

String Formate

在還沒有字串插值之前,工程師組字串多半使用String.Formate()這個方法在組合字串。

官方說明 連結

String.Formate("字串",插入值0,插入值1,插入值2,插入值3,插入值4,....);

範例

string name = "Judy";
string food = "fish";
Console.WriteLine("{0} 吃掉 {1}", name, food);

string formate 教學

複合格式

官方說明:複合格式 – .NET | Microsoft Learn

String.Formate裡面可以對輸出字串時候加以加工

Regular Expression 正規表示法

wiki的說明:連結

微軟的官方教學 英文 中文

簡稱regex

正規表示法使用上挺複雜的,雖然常用,但不適合新手。簡單的說如果對特定模式的字串進行處理,會使用正規表示法處理,用的好就能。

常用情境

  1. 檢查字串是不是符合特定格式,例如Email、身分證字號
  2. 抓取特定模式內的字,例如<p>文章內容</p>
  3. 取代特定模式內的字詞
  4. 查詢特定模式字詞的位置

因為內容複雜,會有另一篇介紹。

0 條留言

提交留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *