Để trim chuỗi trong C#, có thể sử dụng biểu thức chính quy (Regex).
Thiết lập pattern cho regex:
string pattern = "\\s+";
Giả sử chuỗi sau có khoảng trắng ở đầu và cuối:
string input = " Welcome User ";
Sử dụng Regex để thay thế theo pattern:
Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement);
Ví dụ hoàn chỉnh:
Ví dụ
using System;
using System.Text.RegularExpressions;
namespace Demo {
class Program {
static void Main(string[] args) {
string input = " Welcome User ";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Chuỗi gốc: {0}", input);
Console.WriteLine("Chuỗi sau thay thế: {0}", result);
Console.ReadKey();
}
}
}