ตัวอย่างโค้ด (C)
#include <stdio.h>
#include <string.h>
int main() {
char s[50], t;
int i = 0, j = 0;
printf("\nEnter the string to reverse :");
fgets(s, sizeof(s), stdin); // ใช้ fgets แทน gets (ปลอดภัยกว่า)
s[strcspn(s, "\n")] = 0; // ลบ newline
j = strlen(s) - 1;
while (i < j) {
t = s[i];
s[i] = s[j];
s[j] = t;
i++;
j--;
}
printf("\nReverse string is : %s", s);
return 0;
}
ผลลัพธ์
Enter the string to reverse: Hello World
Reverse string is : dlroW olleH
อัลกอริธึม
- คำนวณความยาวสตริง
j = strlen(s) - 1 - Swap ตัวอักษร
s[i]และs[j] i++,j--จนi >= j
C++ Way (Modern)
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string s = "Hello World";
std::reverse(s.begin(), s.end());
std::cout << "Reversed: " << s;
return 0;
}
ใช้ std::reverse จาก <algorithm> สะดวกและปลอดภัยกว่า