User Tools

Site Tools


blog:2025-06-02-001



2025-06-02 C# 將字串中[ 與 ] 替換為 _

  • 在 C# 中,可以使用 string.Replace 方法來將字串中的特定字符進行替換。要將字串中的 [ 和 ] 替換為 _,可以按照以下方式進行操作。

示例代碼

  • 以下是一個示例代碼,展示如何將字串中的 [ 和 ] 替換為 _:
  • using System;
    
    class Program
    {
        static void Main()
        {
            string originalString = "This is a [sample] string with [brackets].";
            
            // 替換 [ 和 ] 為 _
            string modifiedString = originalString.Replace("[", "_").Replace("]", "_");
            
            Console.WriteLine("原始字串: " + originalString);
            Console.WriteLine("修改後的字串: " + modifiedString);
        }
    }

說明

  • 原始字串:
    • originalString 是要進行替換的原始字串。
  • 使用 Replace 方法:
    • originalString.Replace(“[”, “_”) 將所有的 [ 替換為 _。
    • 接著再使用 .Replace(“]”, “_”) 將所有的 ] 替換為 _。

輸出結果:

  • 最後,將修改後的字串輸出到控制台。
  • 輸出示例
    • 如果原始字串為 “This is a [sample] string with [brackets].”,則輸出結果將是:
    • 原始字串: This is a [sample] string with [brackets].
    • 修改後的字串: This is a _sample_ string with _brackets_.
  • 這樣就完成了在 C# 中將字串中的 [ 和 ] 替換為 _ 的操作!

TAGS

  • 30 person(s) visited this page until now.

blog/2025-06-02-001.txt · Last modified: 2025/06/02 10:56 by jethro