تحديات برمجيةالتحدي الثاني - حل التمرين الثالث بلغة C++
المطلوب
قم بتعريف دالة إسمها DoubleChars
, نمرر لها نص عند إستدعاءها فتعيد لنا نسخة من هذا النص كل حرف فيها مكرر مرتين.
مثال: إذا قمنا باستخدام الدالة DoubleChars()
و تمرير النص "Iron Man"
فإنها سترجع النص "IIrroonn MMaann"
.
الحل بلغة C++
#include <iostream>
#include <string>
std::string doubleChars(std::string text) {
std::string newText = "";
for (int i = 0; i < text.length(); i++)
{
newText += text[i];
newText += text[i];
}
return newText;
}
int main() {
std::string text = "Iron Man";
std::string newText = doubleChars(text);
std::cout << "Before: " << text << "\n";
std::cout << "After: " << newText << "\n";
char end; std::cin >> end;
return 0;
}
#include <iostream>
#include <string>
std::string doubleChars(std::string text) {
std::string newText = "";
for (int i = 0; i < text.length(); i++)
{
newText += text[i];
newText += text[i];
}
return newText;
}
int main() {
std::string text = "Iron Man";
std::string newText = doubleChars(text);
std::cout << "Before: " << text << "\n";
std::cout << "After: " << newText << "\n";
char end; std::cin >> end;
return 0;
}
سنحصل على النتيجة التالية عند التشغيل.
Before: Iron Man After: IIrroonn MMaann