المطلوب
قم بتعريف دالة إسمها PrintWordsOccurence, نمرر لها نص عند إستدعاءها فتقوم بطباعة كم مرة تكررت كل كلمة في هذا النص.
مثال: إذا قمنا باستخدام الدالة PrintWordsOccurence() و تمرير النص "I am happy. I am a doctor. I like chocolate." فإنها ستطبع النتيجة التالية.
[3] I [2] am [1] happy. [1] a [1] doctor. [1] like [1] chocolate.
الحل بلغة C
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define MAX_SIZE 100
void printWordsOccurence(char * s) {
if (s[0] == '\0')
{
printf("There is no text!");
}
char text[MAX_SIZE];
char word[MAX_SIZE];
int index;
int beginOfNextWord = 0;
int endOfNextWord = 0;
int wordsCounter;
// Create a copy from the original string
for (int i = 0; i < strlen(s); i++)
{
text[i] = s[i];
}
text[strlen(s)] = '\0';
// walk through all charaters in the string
for (int i = 0; i < strlen(text); i++)
{
if (text[i] != ' ')
{
wordsCounter = 1;
// store first occurence of the word, then remove it
index = 0;
int j = i;
for (; text[j] != ' ' && text[j] != '\0'; j++)
{
word[index] = text[j];
index++;
text[j] = ' ';
}
// remove the reset of copy of the same word
for (; j < strlen(text); j++)
{
bool shouldClear = true;
for (int k = 0; k < strlen(word) && shouldClear == true; k++)
{
if (word[k] != text[j+k])
{
shouldClear = false;
}
}
if (shouldClear)
{
for (int k = 0; k < strlen(word); k++)
{
text[j+k] = ' ';
}
wordsCounter++;
}
}
word[index] = '\0';
printf("[%d] %s\n", wordsCounter, word);
}
}
}
void main() {
char * text = "I am happy. I am a doctor. I like chocolate.";
printWordsOccurence(text);
}
سنحصل على النتيجة التالية عند التشغيل.
[3] I [2] am [1] happy. [1] a [1] doctor. [1] like [1] chocolate.


محرر الويب
نظام الألوان
محول الوحدات
محلل عناوين الشبكات