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

จะแทนที่หลายช่องว่างด้วยช่องว่างเดียวใน C # ได้อย่างไร


มีหลายวิธีในการแทนที่หลายช่องว่างด้วยช่องว่างเดียวใน C#

String.Replace − ส่งกลับสตริงใหม่ที่อักขระ Unicode ที่ระบุหรือสตริงที่ระบุในสตริงปัจจุบันทั้งหมดถูกแทนที่ด้วยอักขระหรือสตริง Unicode ที่ระบุอื่น

แทนที่ (สตริง สตริง บูลีน CultureInfo)

String.Join เชื่อมองค์ประกอบของอาร์เรย์ที่ระบุหรือสมาชิกของคอลเล็กชัน โดยใช้ตัวคั่นที่ระบุระหว่างแต่ละองค์ประกอบหรือสมาชิก

Regex.Replace −ในสตริงอินพุตที่ระบุ แทนที่สตริงที่ตรงกับรูปแบบนิพจน์ทั่วไปด้วยสตริงการแทนที่ที่ระบุ

ตัวอย่างการใช้ Regex

ตัวอย่าง

using System;
using System.Text.RegularExpressions;
namespace DemoApplication{
   class Program{
      public static void Main(){
         string stringWithMulipleSpaces = "Hello World. Hi Everyone";
         Console.WriteLine($"String with multiples spaces:
            {stringWithMulipleSpaces}");
         string stringWithSingleSpace = Regex.Replace(stringWithMulipleSpaces, @"\s+", " ");
         Console.WriteLine($"String with single space: {stringWithSingleSpace}");
         Console.ReadLine();
      }
   }
}

ผลลัพธ์

ผลลัพธ์ของโปรแกรมข้างต้นคือ

String with multiples spaces: Hello World. Hi Everyone
String with single space: Hello World. Hi Everyone

ในตัวอย่างด้านบน Regex.Replace เราได้ระบุช่องว่างเพิ่มเติมและแทนที่ด้วยช่องว่างเดียว

ตัวอย่างการใช้ string.Join

ตัวอย่าง

using System;
namespace DemoApplication{
   class Program{
      public static void Main(){
         string stringWithMulipleSpaces = "Hello World. Hi Everyone";
         Console.WriteLine($"String with multiples spaces:
         {stringWithMulipleSpaces}");
         string stringWithSingleSpace = string.Join(" ",
         stringWithMulipleSpaces.Split(new char[] { ' ' },
         StringSplitOptions.RemoveEmptyEntries));
         Console.WriteLine($"String with single space: {stringWithSingleSpace}");
         Console.ReadLine();
      }
   }
}

ผลลัพธ์

ผลลัพธ์ของโปรแกรมข้างต้นคือ

String with multiples spaces: Hello World. Hi Everyone
String with single space: Hello World. Hi Everyone

ในด้านบนนี้ เรากำลังแบ่งข้อความด้วยช่องว่างหลายช่องโดยใช้วิธี Split และต่อมารวมอาร์เรย์ที่แยกออกโดยใช้วิธีการเข้าร่วมด้วยช่องว่างเดียว