User Tools

Site Tools


blog:2025-06-19-001

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

blog:2025-06-19-001 [2025/06/19 14:26] (current)
jethro created
Line 1: Line 1:
 +~~NOTOC~~
 +====== 2025-06-19 C# String 取得':'​ 字元後的字串 ======
 +  * 在 C# 中,若要從一個字串中取得 ':'​ 字元後的部分,可以使用 String 類別中的方法,例如 IndexOf 和 Substring。以下是一些示例代碼,展示如何實現這一功能。
 +===== 方法 1: 使用 IndexOf 和 Substring =====
 +  * <sxh c#>​string input = "​example:​text";​ // 你的輸入字串
 +int colonIndex = input.IndexOf(':'​);​ // 找到 ':'​ 的索引
 +
 +if (colonIndex != -1) // 確保找到了 ':'​
 +{
 +    string result = input.Substring(colonIndex + 1); // 取得 ':'​ 後的字串
 +    Console.WriteLine(result);​ // 輸出結果
 +}
 +else
 +{
 +    Console.WriteLine("':'​ 字元未找到"​);​
 +}</​sxh>​
 +===== 方法 2: 使用 Split 方法 =====
 +  * 另一種方法是使用 Split 方法,將字串分割為陣列,然後取出 ':'​ 後的部分。
 +  * <sxh c#>​string input = "​example:​text";​ // 你的輸入字串
 +string[] parts = input.Split(':'​);​ // 根據 ':'​ 分割字串
 +
 +if (parts.Length > 1) // 確保有 ':'​ 的存在
 +{
 +    string result = parts[1]; // 取得 ':'​ 後的部分
 +    Console.WriteLine(result);​ // 輸出結果
 +}
 +else
 +{
 +    Console.WriteLine("':'​ 字元未找到"​);​
 +}</​sxh>​
 +===== 方法 3: 使用 LastIndexOf(如果有多個 ':'​) =====
 +  * 如果字串中可能有多個 ':'​,並且你想要獲取最後一個 ':'​ 後的部分,可以使用 LastIndexOf 方法。
 +  * <sxh c#>​string input = "​example:​text:​moretext";​ // 你的輸入字串
 +int lastColonIndex = input.LastIndexOf(':'​);​ // 找到最後一個 ':'​ 的索引
 +
 +if (lastColonIndex != -1) // 確保找到了 ':'​
 +{
 +    string result = input.Substring(lastColonIndex + 1); // 取得最後一個 ':'​ 後的字串
 +    Console.WriteLine(result);​ // 輸出結果
 +}
 +else
 +{
 +    Console.WriteLine("':'​ 字元未找到"​);​
 +}</​sxh>​
 +===== 總結 =====
 +  * 這三種方法都可以用來獲取 ':'​ 字元後的字串,根據具體需求選擇合適的方法。使用 IndexOf 和 Substring 是最常見的方式,而 Split 方法則提供了簡單的分割功能。若有多個 ':'​,則可考慮使用 LastIndexOf。
 +===== TAGS =====
 +  * 
 +====== ======
 +  * {{counter}} person(s) visited this page until now.
 +  * [[:​memo:​index|Back]]
 +====== ======
 +<​html><​!-- ​
 +PDF for A4-Portrait:​ {{pdfjs 50%,450px > xxx.pdf?​page-fit}}
 +PDF for A4-Landscape:​ {{pdfjs 500px,700px > xxx.pdf?​page-fit}}
 +PDF for iPad Note: {{pdfjs 700px,500px > xxx.pdf?​page-fit}}
 +
 +Youtube: {{youtube>​large:​XXXXX}}
 +Code Highlight: <sxh php; first-line: 70; highlight: [89,92]; title: New title attribute in action>
 +
 +--></​html>​
  
blog/2025-06-19-001.txt · Last modified: 2025/06/19 14:26 by jethro