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

โปรแกรม C# นับจำนวนคำที่ซ้ำในสตริง

ใช้เมธอด IndexOf() ในลูป while เพื่อหาตำแหน่งของคำที่ต้องการนับ

อัลกอริทึม

while ((index = str.IndexOf(pattern, index)) != -1) {
    index += pattern.Length;
    count++;
}

ตัวอย่างโค้ดเต็ม

using System;
class Program {
    static void Main() {
        string str = "Hello World! Hello!";
        Console.WriteLine("Occurrence: " + Check.CheckOccurrences(str, "Hello"));
    }
}
public static class Check {
    public static int CheckOccurrences(string str1, string pattern) {
        int count = 0;
        int index = 0;
        while ((index = str1.IndexOf(pattern, index)) != -1) {
            index += pattern.Length;
            count++;
        }
        return count;
    }
}

ผลลัพธ์

Occurrence: 2

คำอธิบาย: "Hello World! Hello!" มีคำว่า "Hello" 2 ครั้ง IndexOf คืน -1 ถ้าไม่เจอ การบวก pattern.Length ทำให้ข้ามคำที่เจอแล้วไปหาต่อ