تحديات برمجيةالتحدي الثالث - حل التمرين الخامس بلغة C++
المطلوب
قم بإنشاء برنامج يطلب من المستخدم إدخال نصّين, بعدها يقوم بطباعة ما إن كان النص الأول ينتهي بالنص الثاني أم لا.
مثال
Enter text 1: Welcome to my world Enter text 2: world -------------------------------- Text 1 is end with 'world'
الحل بلغة C++
#include <iostream>
#include <string>
#include <stdbool.h>
int main() {
std::string text1, text2;
int text2Counter = 0;
bool found = true;
std::cout << "Enter text 1: ";
getline(std::cin, text1);
std::cout << "Enter text 2: ";
getline(std::cin, text2);
for (int i = text1.length() - text2.length(); i < text1.length() && found == true; i++)
{
if (text1[i] != text2[text2Counter])
{
found = false;
}
text2Counter++;
}
std::cout << "--------------------------------\n";
if (found)
{
std::cout << "Text 1 end with '" << text2 << "'";
}
else
{
std::cout << "Text 1 is not end with '" << text2 << "'";
}
char end; std::cin >> end;
return 0;
}
#include <iostream>
#include <string>
#include <stdbool.h>
int main() {
std::string text1, text2;
int text2Counter = 0;
bool found = true;
std::cout << "Enter text 1: ";
getline(std::cin, text1);
std::cout << "Enter text 2: ";
getline(std::cin, text2);
for (int i = text1.length() - text2.length(); i < text1.length() && found == true; i++)
{
if (text1[i] != text2[text2Counter])
{
found = false;
}
text2Counter++;
}
std::cout << "--------------------------------\n";
if (found)
{
std::cout << "Text 1 end with '" << text2 << "'";
}
else
{
std::cout << "Text 1 is not end with '" << text2 << "'";
}
char end; std::cin >> end;
return 0;
}
سنحصل على النتيجة التالية في حال تم إدخال نفس القيم التي تم تعليمها باللون الأصفر عند التشغيل.
Enter text 1: Welcome to my world
Enter text 2: world
--------------------------------
Text 1 is end with 'world'
Enter text 2: world
--------------------------------
Text 1 is end with 'world'