تحديات برمجيةالتحدي الثاني - حل التمرين الثالث بلغة جافا
المطلوب
قم بتعريف دالة إسمها DoubleChars
, نمرر لها نص عند إستدعاءها فتعيد لنا نسخة من هذا النص كل حرف فيها مكرر مرتين.
مثال: إذا قمنا باستخدام الدالة DoubleChars()
و تمرير النص "Iron Man"
فإنها سترجع النص "IIrroonn MMaann"
.
الحل بلغة جافا
public class Main {
public static String doubleChars(String text) {
String newText = "";
for (int i = 0; i < text.length(); i++)
{
newText += text.charAt(i) + "" + text.charAt(i);
}
return newText;
}
public static void main(String[] args) {
String text = "Iron Man";
String newText = doubleChars(text);
System.out.println("Before: " + text);
System.out.println("After: " + newText);
}
}
public class Main {
public static String doubleChars(String text) {
String newText = "";
for (int i = 0; i < text.length(); i++)
{
newText += text.charAt(i) + "" + text.charAt(i);
}
return newText;
}
public static void main(String[] args) {
String text = "Iron Man";
String newText = doubleChars(text);
System.out.println("Before: " + text);
System.out.println("After: " + newText);
}
}
سنحصل على النتيجة التالية عند التشغيل.
Before: Iron Man After: IIrroonn MMaann