Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C พิมพ์สตริงย้อนกลับ (Reverse String) ด้วย for loop และ strrev()


วิธีที่ 1: ใช้ for loop (Manual Reverse)

#include <stdio.h>
int main() {
    char str[100];
    int i = 0;
    
    printf("Enter message: ");
    while((str[i] = getchar()) != '\n' && i < 99) i++;
    str[i] = '\0';
    
    printf("Reversed: ");
    for(i--; i >= 0; i--) putchar(str[i]);
    putchar('\n');
    return 0;
}

ผลลัพธ์

enter the message: Hi welcome to my world
the reverse statement is: dlrow ym ot emoclew iH

วิธีที่ 2: ใช้ strrev() จาก string.h

#include <stdio.h>
#include <string.h>
int main() {
    char str[50];
    printf("Enter string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = 0;
    
    strrev(str);  // non-standard, บาง compiler ไม่มี
    printf("Reversed: %s\n", str);
    return 0;
}

ผลลัพธ์

Enter String to be reversed: Hi welcome to tutorials Point
The reversed string is: tnioP slairotut ot emoclew iH

หมายเหตุ: strrev() ไม่ใช่ standard C (อยู่ใน string.h ของบาง compiler เท่านั้น) ควรเขียนเองด้วย loop เพื่อ portability