如何在 C# 中替换字符串中的换行符?
csharpserver side programmingprogramming更新于 2025/6/28 18:52:17
假设我们需要从下面的字符串中删除换行符、空格和制表符。
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) 来执行相同的操作。正则表达式位于 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

