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

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

المطلوب

قم بتعريف دالة إسمها DoubleChars, نمرر لها نص عند إستدعاءها فتعيد لنا نسخة من هذا النص كل حرف فيها مكرر مرتين.

مثال: إذا قمنا باستخدام الدالة DoubleChars() و تمرير النص "Iron Man" فإنها سترجع النص "IIrroonn MMaann".


الحل بلغة C

#include <stdio.h>
#include <string.h>
char * doubleChars(char * text) {
char * newText = (char*)malloc(sizeof(strlen(text) * 2) + 1);
int nextIndex = 0;
int i = 0;
while ( text[i] != '\0' )
{
newText[nextIndex] = text[i];
newText[nextIndex + 1] = text[i];
nextIndex += 2;
i++;
}
newText[nextIndex] = '\0';
return newText;
}
void main() {
char * text = "Iron Man";
char * newText = doubleChars(text);
printf("Before: %s \n", text);
printf("After: %s \n", newText);
}
#include <stdio.h> #include <string.h> char * doubleChars(char * text) { char * newText = (char*)malloc(sizeof(strlen(text) * 2) + 1); int nextIndex = 0; int i = 0; while ( text[i] != '\0' ) { newText[nextIndex] = text[i]; newText[nextIndex + 1] = text[i]; nextIndex += 2; i++; } newText[nextIndex] = '\0'; return newText; } void main() { char * text = "Iron Man"; char * newText = doubleChars(text); printf("Before: %s \n", text); printf("After: %s \n", newText); }

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

Before: Iron Man
After:  IIrroonn  MMaann
		

الدورات

أدوات مساعدة

أقسام الموقع

دورات
مقالات كتب مشاريع أسئلة