Giới thiệu
Phương thức String.IndexOf() trong C# tìm chỉ số (zero-based) của lần xuất hiện đầu tiên của một ký tự Unicode hoặc chuỗi con trong chuỗi hiện tại. Trả về -1 nếu không tìm thấy.
Cú pháp phổ biến
public int IndexOf (string value); public int IndexOf (char value); public int IndexOf (string value, int startIndex); public int IndexOf (string value, int startIndex, int count); public int IndexOf (string value, StringComparison comparisonType);
Ví dụ 1: Tìm ký tự trong chuỗi
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 của String 1 = " + str1.GetHashCode());
Console.WriteLine("Index của ký tự 'o' trong str1 = " + str1.IndexOf("o"));
Console.WriteLine("\nString 2 = " + str2);
Console.WriteLine("HashCode của String 2 = " + str2.GetHashCode());
Console.WriteLine("Index của ký tự 'o' trong str2 = " + str2.IndexOf("o"));
bool res = str1.Contains(str2);
if (res)
Console.WriteLine("Found!");
else
Console.WriteLine("Not found!");
}
}
Đầu ra ví dụ 1
String 1 = Jacob HashCode của String 1 = -790718923 Index của ký tự 'o' trong str1 = 3 String 2 = John HashCode của String 2 = -1505962600 Index của ký tự 'o' trong str2 = 1 Not found!
Ví dụ 2: Tìm ký tự không tồn tại
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 của String 1 = " + str1.GetHashCode());
Console.WriteLine("Index của ký tự 'k' trong str1 = " + str1.IndexOf("k"));
Console.WriteLine("\nString 2 = " + str2);
Console.WriteLine("HashCode của String 2 = " + str2.GetHashCode());
Console.WriteLine("Index của ký tự 'k' trong str2 = " + str2.IndexOf("k"));
bool res = str1.Contains(str2);
if (res)
Console.WriteLine("Found!");
else
Console.WriteLine("Not found!");
}
}
Đầu ra ví dụ 2
String 1 = Kevin HashCode của String 1 = -768104063 Index của ký tự 'k' trong str1 = -1 String 2 = Evin HashCode của String 2 = 1223510568 Index của ký tự 'k' trong str2 = -1 Not found!
Các overload hữu ích khác
string text = "Hello World Hello";
// Tìm từ vị trí bắt đầu
int idx1 = text.IndexOf("Hello", 6); // 12 (bỏ qua "Hello " đầu)
// Tìm trong phạm vi
int idx2 = text.IndexOf("o", 5, 6); // 7 (tìm 'o' từ index 5, dài 6 ký tự)
// So sánh không phân biệt chữ hoa/thường
int idx3 = text.IndexOf("hello", StringComparison.OrdinalIgnoreCase); // 0
// Tìm cuối cùng (LastIndexOf)
int last = text.LastIndexOf("Hello"); // 12
Lưu ý quan trọng
- Trả về -1 nếu không tìm thấy (không ném exception).
- Mặc định so sánh ordinal (phân biệt chữ hoa/thường, so sánh giá trị Unicode).
- Dùng
StringComparison.OrdinalIgnoreCasecho tìm kiếm không phân biệt hoa/thường. - Dùng
StringComparison.CurrentCulturecho tìm kiếm theo quy tắc ngôn ngữ (ví dụ: "ß" = "ss" trong tiếng Đức). IndexOf(char)nhanh hơnIndexOf(string)cho tìm ký tự đơn.
So sánh IndexOf vs Contains vs StartsWith/EndsWith
| Phương thức | Trả về | Dùng khi |
|---|---|---|
| IndexOf | int (vị trí) | Cần biết vị trí, hoặc tìm nhiều lần |
| Contains | bool | Chỉ cần biết có/không |
| StartsWith | bool | Kiểm tra tiền tố |
| EndsWith | bool | Kiểm tra hậu tố |
Ứng dụng thực tế
- Parsing: tách chuỗi theo delimiter (
str.Substring(0, str.IndexOf(":"))). - Validation: kiểm tra ký tự cấm, định dạng email.
- Tìm kiếm văn bản, highlight từ khóa.
- Xử lý log, CSV, protocol parsing.