如何在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 红包祝福语简短10字
18 周六早晨祝福语简短