Computer >> Máy Tính >  >> Lập trình >> C#

Làm cách nào để thay thế ngắt dòng trong một chuỗi trong C #?

Hãy để chúng tôi thực hiện, chúng tôi phải loại bỏ các ngắt dòng, dấu cách và khoảng cách tab khỏi chuỗi bên dưới.

remove.jpg

Ví dụ

Chúng ta có thể sử dụng phương thức mở rộng Replace () của chuỗi để làm điều đó.

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();
      }
   }
}

Đầu ra

Đầu ra của đoạn mã trên là

Hello _ beautiful _ world

Ví dụ

Chúng ta cũng có thể sử dụng Regex để thực hiện thao tác tương tự. Regex có sẵn trong không gian tên 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();
      }
   }
}

Đầu ra

Đầu ra của đoạn mã trên là

Hello _ beautiful _ world