如何在 C# 中替換字串中的換行符?
我們以從以下字串中消除換行符、空格和製表符為例。
eliminate.jpg
示例
我們可利用字串的 Replace() 擴充套件方法來執行此操作。
using System;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
string testString = "Hello
\r beautiful
\t world";
string replacedValue = testString.Replace("
\r", "_").Replace("
\t", "_");
Console.WriteLine(replacedValue);
Console.ReadLine();
}
}
}輸出
以上程式碼的輸出如下
Hello _ beautiful _ world
示例
我們也可利用 Regex 執行相同的操作。Regex 在 System.Text.RegularExpressions 名稱空間中。
using System;
using System.Text.RegularExpressions;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
string testString = "Hello
\r beautiful
\t world";
string replacedValue = Regex.Replace(testString, @"
\r|
\t", "_");
Console.WriteLine(replacedValue);
Console.ReadLine();
}
}
}輸出
以上程式碼的輸出如下
Hello _ beautiful _ world
廣告
















