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

โปรแกรม C# ตรวจสอบ URL ในสตริง

ใช้เมธอด StartsWith() ตรวจสอบว่าสตริงขึ้นต้นด้วย URL pattern ที่กำหนด

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

using System;
class Demo {
    static void Main() {
        string input = "https://example.com/new.html";
        // ตรวจสอบทั้ง www และ non-www
        if (input.StartsWith("https://www.example.com") || 
            input.StartsWith("https://example.com")) {
            Console.WriteLine(true);
        }
    }
}

ผลลัพธ์

True

การขยาย: สำหรับ URL validation จริง ควรใช้ Regex หรือ Uri.TryCreate()

// ใช้ Uri class (แนะนำ)
if (Uri.TryCreate(input, UriKind.Absolute, out Uri uriResult) 
    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)) {
    // Valid URL
}