เมธอด String.IndexOf() ใน C# ใช้สำหรับค้นหาตำแหน่ง (ดัชนี 0-based) ของตัวอักษรหรือสตริงย่อยที่พบครั้งแรก ภายในสตริง คืนค่า -1 หากไม่พบ
ไวยากรณ์ (Syntax)
public int IndexOf (string val);
val— สตริงที่ต้องการค้นหา
หมายเหตุ: มี overload อื่นๆ เช่น IndexOf(char), IndexOf(string, int startIndex), IndexOf(string, int, int), IndexOf(string, StringComparison) ฯลฯ
ตัวอย่างที่ 1: ค้นหาตัวอักษรในสตริง
using System;
public class Demo
{
public static void Main(String[] args)
{
string str1 = "Jacob";
string str2 = "John";
Console.WriteLine("String 1 = " + str1);
Console.WriteLine("HashCode of String 1 = " + str1.GetHashCode());
Console.WriteLine("Index of 'o' in str1 = " + str1.IndexOf("o"));
Console.WriteLine("\nString 2 = " + str2);
Console.WriteLine("HashCode of String 2 = " + str2.GetHashCode());
Console.WriteLine("Index of 'o' in str2 = " + str2.IndexOf("o"));
bool res = str1.Contains(str2);
if (res)
Console.WriteLine("Found!");
else
Console.WriteLine("Not found!");
}
}
ผลลัพธ์
String 1 = Jacob HashCode of String 1 = -790718923 Index of 'o' in str1 = 3 String 2 = John HashCode of String 2 = -1505962600 Index of 'o' in str2 = 1 Not found!
ตัวอย่างที่ 2: ค้นหาตัวอักษรที่ไม่มีในสตริง
using System;
public class Demo
{
public static void Main(String[] args)
{
string str1 = "Kevin";
string str2 = "Evin";
Console.WriteLine("String 1 = " + str1);
Console.WriteLine("HashCode of String 1 = " + str1.GetHashCode());
Console.WriteLine("Index of 'k' in str1 = " + str1.IndexOf("k"));
Console.WriteLine("\nString 2 = " + str2);
Console.WriteLine("HashCode of String 2 = " + str2.GetHashCode());
Console.WriteLine("Index of 'k' in str2 = " + str2.IndexOf("k"));
bool res = str1.Contains(str2);
if (res)
Console.WriteLine("Found!");
else
Console.WriteLine("Not found!");
}
}
ผลลัพธ์
String 1 = Kevin HashCode of String 1 = -768104063 Index of 'k' in str1 = -1 String 2 = Evin HashCode of String 2 = 1223510568 Index of 'k' in str2 = -1 Not found!
Overload ที่ใช้บ่อยและควรรู้
| เมธอด | คำอธิบาย |
|---|---|
| IndexOf(char value) | ค้นหาตัวอักษรเดี่ยว |
| IndexOf(string value) | ค้นหาสตริงย่อย |
| IndexOf(string value, int startIndex) | ค้นหาเริ่มจากตำแหน่ง startIndex |
| IndexOf(string value, int startIndex, int count) | ค้นหาในช่วงที่กำหนด |
| IndexOf(string value, StringComparison) | ค้นหาพร้อมระบุกฎการเปรียบเทียบ (เช่น OrdinalIgnoreCase) |
ข้อสังเกตสำคัญ
- คืนค่า -1 หากไม่พบ — ต้องตรวจสอบเสมอก่อนใช้ดัชนี
- ค้นหาแบบ Case-Sensitive โดยค่าเริ่มต้น — ใช้
StringComparison.OrdinalIgnoreCaseเพื่อไม่สนใจตัวพิมพ์เล็ก/ใหญ่ - สำหรับการค้นหาครั้งสุดท้าย ใช้
LastIndexOf() - ประสิทธิภาพ O(n) — หากค้นหาบ่อยในสตริงยาว ควรพิจารณา
StringBuilderหรือดัชนี้นำหน้า