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

ตรวจสอบว่าสตริงเริ่มต้นด้วย substring เฉพาะใน Java

String แทนสตริงตัวอักษร ทุก string literal เป็นอินสแตนซ์ของ String class สตริงเป็น คงที่ (immutable) ไม่เปลี่ยนค่าได้หลังสร้าง

ใช้เมธอด startsWith() ตรวจสอบว่าสตริงขึ้นต้นด้วย substring ที่ระบุ คืนค่า boolean (true/false)

ไวยากรณ์

public boolean startsWith(String prefix)

ตัวอย่าง: ตรวจสอบคำหน้า

public class StringStartsWithSubStringTest {
    public static void main(String[] args) {
        String str = "WelcomeToTutorialsPoint";
        if (str.startsWith("Welcome")) {
            System.out.println("Begins with the specified word!");
        } else {
            System.out.println("Does not begin with the specified word!");
        }
    }
}

ผลลัพธ์

Begins with the specified word!

เมธอดที่เกี่ยวข้อง: endsWith() (ตรวจคำท้าย), contains() (ตรวจสตริงย่อยทั่วไป), startsWith(prefix, offset) (ตรวจจากตำแหน่งที่ระบุ)