C-Sharp Tìm số lần lập lại của mạo thừ 'the' xuất hiện trong câu. (C-Sharp how to find the frequency of the word in a given sentence?)

Đây là một trong những bài tập cơ bản của C-Sharp khi mới bắt đầu học ngôn ngữ lập trình này, bài tập yêu cầu bạn phải tìm số lần xuất hiện của mạo từ 'the' trong câu.

C-Sharp how to find the frequency of the word in a given sentence


C-Sharp Example:
-----------------------
    using System;
    class program
    {
        public static void Main()
        {
            string s1;
            Console.WriteLine("Enter the String : ");
            s1 = Console.ReadLine();
            Console.WriteLine(counting.CountStringOccurrences(s1, "the"));
            Console.ReadLine();
        }
    }

    public static class counting
    {
        public static int CountStringOccurrences(string text, string pattern)
        {

            int count = 0;
            int i = 0;
            while ((i = text.IndexOf(pattern, i)) != -1)
            {
                i += pattern.Length;
                count++;
            }

            return count;
        }

    }

---------------------------------





No comments:

Post a Comment