如何在 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
广告
















