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

โปรแกรม C# แยกและรวมสตริง (Split และ Join)

ใช้เมธอด Split() เพื่อแยกสตริง และ Join() เพื่อรวมสตริง

สมมติสตริงต้นฉบับ:

string str = "This is our Demo String";

การแยกสตริง (Split)

var arr = str.Split(' ');

ผลลัพธ์จะได้อาร์เรย์: ["This", "is", "our", "Demo", "String"]

การรวมสตริง (Join)

string rest = string.Join(" ", arr.Skip(1));

ใช้ Skip(1) เพื่อข้ามคำแรก ("This") แล้วรวมคำที่เหลือด้วยช่องว่าง

ตัวอย่างโค้ดเต็ม

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
    class MyApplication {
        static void Main(string[] args) {
            string str = "This is our Demo String";
            var arr = str.Split(' ');
            // ข้ามคำแรกและรวมคำที่เหลือ
            string rest = string.Join(" ", arr.Skip(1));
            Console.WriteLine(rest);
        }
    }
}

ผลลัพธ์

is our Demo String

หมายเหตุ: ต้องมี using System.Linq; เพื่อใช้เมธอด Skip()