C# 訪問字串
訪問字串
您可以透過方括號 []
中的索引號來訪問字串中的字元。
此示例列印 myString 中的第一個字元
注意:字串索引從 0 開始:[0] 是第一個字元。[1] 是第二個字元,依此類推。
此示例列印 myString 中的第二個字元 (1)
您還可以透過使用 IndexOf()
方法查詢特定字元在字串中的索引位置
另一個有用的方法是 Substring()
,它從指定的字元位置/索引開始提取字串中的字元,並返回一個新字串。此方法經常與 IndexOf()
一起使用以獲取特定字元位置
示例
// Full name
string name = "John Doe";
// Location of the letter D
int charPos = name.IndexOf("D");
// Get last name
string lastName = name.Substring(charPos);
// Print the result
Console.WriteLine(lastName);