Java String indexOf ()เมธอด
ตัวอย่าง
ค้นหาสตริงสำหรับการเกิดขึ้นครั้งแรกของ "ดาวเคราะห์":
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.indexOf("planet"));
ความหมายและการใช้งาน
เมธอดจะคืน ค่าindexOf()
ตำแหน่งการเกิดขึ้นครั้งแรกของอักขระที่ระบุในสตริง
เคล็ดลับ:ใช้ เมธอด lastIndexOfเพื่อคืนค่าตำแหน่งของอักขระที่ระบุในสตริงที่เกิดขึ้นครั้งล่าสุด
ไวยากรณ์
มี 4 วิธี indexOf():
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
public int indexOf(int char)
public int indexOf(int char, int fromIndex)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
str | A String value, representing the string
to search for |
fromIndex | An int value, representing the index position to start the search from |
char | An int value, representing a single
character, e.g 'A', or a Unicode value |
รายละเอียดทางเทคนิค
ผลตอบแทน: | ค่า ที่int แสดงดัชนีของการเกิดครั้งแรกของอักขระในสตริง หรือ -1 หากไม่เคยเกิดขึ้น |
---|
ตัวอย่างเพิ่มเติม
ตัวอย่าง
ค้นหาการเกิดขึ้นครั้งแรกของตัวอักษร "e" ในสตริง โดยเริ่มจากการค้นหาที่ตำแหน่ง 5:
public class Main {
public static void main(String[] args) {
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.indexOf("e", 5));
}
}
❮ วิธีการสตริง