Programming Basics SQL HTML CSS JavaScript Python C++ Java JavaFX Swing Problem Solving English English Conversations Computer Fundamentals Learn Typing

تحديات برمجيةالتحدي الأول - حل التمرين الرابع بلغة C#

المطلوب

قم بتعريف دالة إسمها CountOccurrences, عند استدعاءها نمرر لها نصيّن, فترجع عدد صحيح يمثل كم مرة النص الثاني مكرر في النص الأول.
بعدها قم بتجربة هذه الدالة في البرنامج مع جعل المستخدم هو من يدخل النصيّن.

مثال: إذا قمنا باستخدام الدالة CountOccurrences() لمعرفة كم مرة تكررت الكلمة cat في النص I like cats. I have one cat called Lola فإنها سترجع الرقم 2.


الحل بلغة C#

using System;
class Program
{
static void Main(string[] args)
{
Console.Write("Enter any text: ");
String text = Console.ReadLine();
Console.Write("Enter word to search occurrences: ");
String keyword = Console.ReadLine();
int result = CountOccurrences(text, keyword);
Console.WriteLine("Total occurrences of '" + keyword + "' is: " + result);
Console.ReadKey();
}
public static int CountOccurrences(String s1, String s2)
{
int counter = 0;
for (int i = 0; i < s1.Length - s2.Length + 1; i++)
{
if (s1.Substring(i, s2.Length).Equals(s2))
{
counter++;
}
}
return counter;
}
}
using System; class Program { static void Main(string[] args) { Console.Write("Enter any text: "); String text = Console.ReadLine(); Console.Write("Enter word to search occurrences: "); String keyword = Console.ReadLine(); int result = CountOccurrences(text, keyword); Console.WriteLine("Total occurrences of '" + keyword + "' is: " + result); Console.ReadKey(); } public static int CountOccurrences(String s1, String s2) { int counter = 0; for (int i = 0; i < s1.Length - s2.Length + 1; i++) { if (s1.Substring(i, s2.Length).Equals(s2)) { counter++; } } return counter; } }

سنحصل على النتيجة التالية في حال تم إدخال نفس القيم التي تم تعليمها باللون الأصفر عند التشغيل.

Enter any text: I like cats. I have one cat called Lola
Enter word to search occurrences: cat
Total occurrences of 'cat' is: 2