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

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

string 字串提供的各種方法

.Contains(要找的字) 包含
.Replace(要換的字, 替換的字) 替換

1
2
3
4
string s = "小王在哪裡?";
if (s.Contains("小王")) {
    s = s.Replace("小王", "張三");
}
  • Substring(開始的索引, 結束的索引):截取字串
    .Substring(1, 2) 截取 index[1] 到 index[2] 的字串
1
2
string s = "今天天氣好好啊";
s= s.Substring(1, 2); //輸出:天天

.StartsWith(開始的字):判斷以…開始
.EndsWith(結束的字): 判斷以…結束

1
2
3
4
5
6
7
8
9
10
11
12
13
string s = "今天天氣好好啊";
//StartsWith 判斷字串開始的字元
if (s.StartsWith("今天")) {
    Console.WriteLine("Yes"); //輸出:Yes
} else {
    Console.WriteLine("No");
}
//EndsWith 判斷字串結束的字元
if (s.EndsWith("好好啊")) {
    Console.WriteLine("Yes"); //輸出:Yes
} else {
    Console.WriteLine("No");
}

.IndexOf(要找的字):要找的字,是在第一次出現的位置
如果找不到,會回傳 -1

1
2
3
4
5
string s = "今天天氣好好,天啊";
int index = s.IndexOf("天"); //index: 1
int index = s.IndexOf("天", 1); //index: 1,從index[1]開始找,所以包括當前位置的天
int index = s.IndexOf("天", 2); //index: 2,從index[2]開始找
int index = s.IndexOf("哈", 1); //index: -1,找不到

.LastIndexOf(要找的字):要找的字,最後出現的位置

1
2
string s = "今天天氣好好,天啊";
int index = s.LastIndexOf("天"); //index: 7

舉例:LastIndexOf + Substring 找文件夾中的檔名

1
2
3
4
string path = @"c:\a\b\張c\d\e\f\g\張老師張.wav";
int index = path.LastIndexOf('\\'); //找到最後一個斜線
path = path.Substring(index + 1); //截取字串(檔名)
Console.WriteLine(path); //輸出:張老師張.wav

.Trim():去掉字串前後空白
.TrimStart():去掉字串前面空白
.TrimEnd():去掉字串後面空白

string.IsNullOrEmpty(): 判斷字串是否為空或null

1
2
3
4
string s = null;
if (string.IsNullOrEmpty(s)) {
    ...
}

string.Join():將陣列按照指定的字元串接,返回一個字串

1
2
3
string[] names = { "張三", "李四", "王老", "小六" };
string s = string.Join("|", names);
Console.WriteLine(s);//輸出張三|李四|王老|小六

也可以這樣寫

1
string s = string.Join("|", "張三", "李四", "王老", "小六");

因為它是params參數

api/system.string.join?

This post is licensed under CC BY 4.0 by the author.