Đếm tần suất xuất hiện của một từ (substring) trong chuỗi lớn. Sử dụng String.IndexOf trong vòng lặp để tìm vị trí lần lượt.
Mã nguồn
using System;
class Program {
static void Main() {
string str = "Hello World! Hello!";
string pattern = "Hello";
int count = CheckOccurrences(str, pattern);
Console.WriteLine("Số lần xuất hiện: " + count);
}
}
public static class Check {
public static int CheckOccurrences(string text, string pattern) {
if (string.IsNullOrEmpty(pattern)) return 0;
int count = 0;
int index = 0;
// Tìm lần lượt, bắt đầu từ vị trí sau match trước
while ((index = text.IndexOf(pattern, index)) != -1) {
index += pattern.Length; // Nhảy qua từ vừa tìm thấy
count++;
}
return count;
}
}
Kết quả
Số lần xuất hiện: 2
Các trường hợp cần lưu ý
| Chuỗi | Từ tìm | Kết quả | Ghi chú |
|---|---|---|---|
| "Hello Hello" | "Hello" | 2 | Tách biệt bằng space |
| "HelloHello" | "Hello" | 2 | Chồng chéo (overlap) — code trên KHÔNG đếm overlap |
| "aaaa" | "aa" | 2 | IndexOf nhảy qua length → không đếm overlap |
Đếm có overlap (ví dụ "aaaa" tìm "aa" → 3)
int count = 0;
for (int i = 0; i <= text.Length - pattern.Length; i++) {
if (text.Substring(i, pattern.Length) == pattern) count++;
}
Cách LINQ (đơn giản, không overlap)
int count = text.Split(new[] { pattern }, StringSplitOptions.None).Length - 1;
Regex (hỗ trợ word boundary, case-insensitive)
using System.Text.RegularExpressions;
int count = Regex.Matches(text, @"\b" + Regex.Escape(pattern) + @"\b", RegexOptions.IgnoreCase).Count;
// \b = word boundary (ranh giới từ)
Lưu ý
- Code gốc dùng
IndexOf— hiệu năng tốt, không cấp phát mảng. - Mặc định phân biệt chữ hoa/thường — dùng
StringComparison.OrdinalIgnoreCaseoverload nếu cần. IndexOfkhông đếm overlap — phù hợp tìm từ hoàn chỉnh.