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++

#include <iostream>
#include <string>
int CountOccurrences(std::string s1, std::string s2)
{
int counter = 0;
for (int i = 0; i < s1.length() - s2.length() + 1; i++)
{
if (s1.substr(i, s2.length()) == s2)
{
counter++;
}
}
return counter;
}
int main() {
std::string text;
std::string keyword;
std::cout << "Enter any text: ";
getline(std::cin, text);
std::cout << "Enter word to search occurrences: ";
getline(std::cin, keyword);
int result = CountOccurrences(text, keyword);
std::cout << "Total occurrences of '" << keyword << "' is: " << result;
char end; std::cin >> end;
return 0;
}
#include <iostream> #include <string> int CountOccurrences(std::string s1, std::string s2) { int counter = 0; for (int i = 0; i < s1.length() - s2.length() + 1; i++) { if (s1.substr(i, s2.length()) == s2) { counter++; } } return counter; } int main() { std::string text; std::string keyword; std::cout << "Enter any text: "; getline(std::cin, text); std::cout << "Enter word to search occurrences: "; getline(std::cin, keyword); int result = CountOccurrences(text, keyword); std::cout << "Total occurrences of '" << keyword << "' is: " << result; char end; std::cin >> end; return 0; }

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

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