Home [C# 筆記] string 字串提供的各種方法 1
Post
Cancel

[C# 筆記] string 字串提供的各種方法 1

字串提供的各種方法

  • .Length:字串的長度/個數
  • .ToUpper():轉大寫
  • .ToLower():轉小寫

  • .Equals(): 兩字串比較,區分大小寫
  • StringComparison.OrdinalIgnoreCase:忽略大小寫 s1.Equals(s2,StringComparison.OrdinalIgnoreCase) //忽略大小寫

範例:使用 Equals 比較字串是否相同,並忽略大小寫

1
2
3
4
string s1 = "c#";
string s2 = "C#";
Console.WriteLine(s1.Equals(s2));  //輸出:false
Console.WriteLine(s1.Equals(s2,StringComparison.OrdinalIgnoreCase)); //輸出:true

字串的分割 Split

  • string[] Split(params char[] separator)
    將字串 按照指定的字元分割為 字串陣列
  • string[] Split(char[] separator, StringSplitOptions options)
    將字串按照指定的char[] 分割,分割為字串陣列
    options 選擇StringSplitOptions.RemoveEmptyEntries,會移除結果中的空白字串

範列:將字串只保留英數字,移除掉符號和包含空白

1
2
3
string s = "a + b ...s ==d,4-3 -T*d, a/";
char[] chs = {' ', '+', '-','.','=','/','*',',' }; //不要的字元
string[] str = s.Split(chs, StringSplitOptions.RemoveEmptyEntries); //分割字串,移除空白

這樣寫也可以(寫成一行):

1
string[] str = s.Split(new char[] {' ', '+', '-', '.', '=', '/', '*', ',' }, StringSplitOptions.RemoveEmptyEntries); //分割字串,移除空白

練習:將字串”2008-08-08”輸出為”2008年08月08日”;

1
2
3
string sDate = "2008-08-08";
string[] date = sDate.Split('-'); //以-分割
Console.WriteLine($"{date[0]}{date[1]}{date[2]}日");
This post is licensed under CC BY 4.0 by the author.