Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ลบช่องว่างด้วย C# Regex

สมมติว่าเราต้องการลบช่องว่างจากสตริง str1 ดังนี้:

string str1 = "Brad Pitt";

ตอนนี้ ให้ใช้ Regex.Replace เพื่อแทนที่ช่องว่างด้วยค่าว่าง โดยเราได้ใช้ System.Text.RegularExpressions

string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");

มาดูตัวอย่างทั้งหมดกัน

ตัวอย่าง

using System;
using System.Text.RegularExpressions;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "Brad Pitt";
            Console.WriteLine(str1);
            string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");
            Console.WriteLine(str2);
        }
    }
}

ผลลัพธ์

Brad Pitt
BradPitt