如何在C#中替换字符串中的换行符?
让我们以为,必须从下面的字符串中消除换行符,空格和制表符空间。
消除.jpg
示例
我们可以利用Replace()字符串的扩展方法来做到这一点。
using System;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
string testString = "Hello \n\r beautiful \n\t world";
string replacedValue = testString.Replace("\n\r", "_").Replace("\n\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 \n\r beautiful \n\t world";
string replacedValue = Regex.Replace(testString, @"\n\r|\n\t", "_");
Console.WriteLine(replacedValue);
Console.ReadLine();
}
}
}输出结果
上面代码的输出是
Hello _ beautiful _ world
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语