Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Thay thế line breaks trong string trong C#

Giả sử cần loại bỏ line breaks, space và tab space từ string.

Ví dụ dùng 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();
        }
    }
}

Kết quả

Hello _ beautiful _ world

Ví dụ dùng Regex

Regex nằm trong namespace 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();
        }
    }
}

Kết quả

Hello _ beautiful _ world