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 <stdio.h>
#include <string.h>
#include <stdbool.h>
#define MAX_SIZE 1000
int countOccurrences(char * text, char * keyword)
{
int count = 0;
bool found;
int textLength = strlen(text);
int keywordLength = strlen(keyword);
for (int i = 0; i <= textLength - keywordLength; i++)
{
found = true;
for (int j = 0; j < keywordLength; j++)
{
if(text[i + j] != keyword[j])
{
found = false;
break;
}
}
if(found == true)
{
count++;
}
}
return count;
}
void main() {
char text[MAX_SIZE];
char keyword[MAX_SIZE];
int count;
printf("Enter any string: ");
gets(text);
printf("Enter word to search occurrences: ");
gets(keyword);
count = countOccurrences(text, keyword);
printf("Total occurrences of '%s': %d", keyword, count);
}
#include <stdio.h> #include <string.h> #include <stdbool.h> #define MAX_SIZE 1000 int countOccurrences(char * text, char * keyword) { int count = 0; bool found; int textLength = strlen(text); int keywordLength = strlen(keyword); for (int i = 0; i <= textLength - keywordLength; i++) { found = true; for (int j = 0; j < keywordLength; j++) { if(text[i + j] != keyword[j]) { found = false; break; } } if(found == true) { count++; } } return count; } void main() { char text[MAX_SIZE]; char keyword[MAX_SIZE]; int count; printf("Enter any string: "); gets(text); printf("Enter word to search occurrences: "); gets(keyword); count = countOccurrences(text, keyword); printf("Total occurrences of '%s': %d", keyword, count); }

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

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