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

تحديات برمجيةالتحدي الثالث - حل التمرين الثالث بلغة C++

المطلوب

قم بتعريف دالة إسمها 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 <iostream>
#include <string>
#include "vector"
void printWordsOccurence(std::string s) {
if (s.empty())
{
return;
}
int counter = 0;
std::string word = "";
std::vector<std::string> words;
// هذه الإضافة سببها هو سواء كان يوجد مسافة فارغة في آخر النص أم لا يوجد, فإنها لن تؤثر على النتيجة
s += " ";
for (int i = 0; i < s.length() - 1; i++)
{
if (s[i] != ' ')
{
word += s[i];
}
else
{
words.push_back(word);
word = "";
}
}
for (int i = 0; i < words.size(); i++)
{
counter = 1;
for (int j = i + 1; j < words.size(); j++)
{
if (words[i] == words[j])
{
counter = counter + 1;
words[j] = "";
}
}
if (words[i] != "")
{
std::cout << "[" << counter << "] " << words[i] << "\n";
}
}
}
int main() {
std::string text = "I am happy. I am a doctor. I like chocolate.";
printWordsOccurence(text);
char end; std::cin >> end;
return 0;
}
#include <iostream> #include <string> #include "vector" void printWordsOccurence(std::string s) { if (s.empty()) { return; } int counter = 0; std::string word = ""; std::vector<std::string> words; // هذه الإضافة سببها هو سواء كان يوجد مسافة فارغة في آخر النص أم لا يوجد, فإنها لن تؤثر على النتيجة s += " "; for (int i = 0; i < s.length() - 1; i++) { if (s[i] != ' ') { word += s[i]; } else { words.push_back(word); word = ""; } } for (int i = 0; i < words.size(); i++) { counter = 1; for (int j = i + 1; j < words.size(); j++) { if (words[i] == words[j]) { counter = counter + 1; words[j] = ""; } } if (words[i] != "") { std::cout << "[" << counter << "] " << words[i] << "\n"; } } } int main() { std::string text = "I am happy. I am a doctor. I like chocolate."; printWordsOccurence(text); char end; std::cin >> end; return 0; }

سنحصل على النتيجة التالية عند التشغيل.

[3] I
[2] am
[1] happy.
[1] a
[1] doctor.
[1] like
[1] chocolate.