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

โปรแกรม C# หา Substring ทั้งหมดในสตริง

ใช้เมธอด Substring(startIndex, length) เพื่อดึง substring ทุกความยาวที่เป็นไปได้

สตริงตัวอย่าง: "xyz"

Substrings ทั้งหมด: x, y, z, xy, yz, xyz

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

using System;
class Demo {
    static void Main() {
        string str = "xyz";
        // i = ความยาวของ substring (1 ถึง length-1)
        for (int i = 1; i < str.Length; i++) {
            // start = ตำแหน่งเริ่มต้น
            for (int start = 0; start <= str.Length - i; start++) {
                string substr = str.Substring(start, i);
                Console.WriteLine(substr);
            }
        }
    }
}

ผลลัพธ์

x
y
z
xy
yz

หมายเหตุ: โค้ดนี้ไม่รวม substring ความยาวเต็ม (xyz) เพราะลูป i วนจน i < str.Length หากต้องการรวมเต็ม ให้เปลี่ยนเป็น i <= str.Length