นี่คือตัวอย่างการกลับสตริงในภาษา C
ตัวอย่าง
#include<stdio.h>
#include<string.h>
int main() {
char s[50], t;
int i = 0, j = 0;
printf("\nEnter the string to reverse :");
gets(s);
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: Here is the input string. Reverse string is : .gnirts tupni eht si ereH
ในโปรแกรมข้างต้น โค้ดจริงเพื่อย้อนกลับสตริงมีอยู่ใน main() มีการประกาศอาร์เรย์ประเภทถ่าน char[50] ซึ่งจะเก็บสตริงอินพุตที่ผู้ใช้กำหนด
จากนั้น เรากำลังคำนวณความยาวของสตริงโดยใช้ฟังก์ชันไลบรารี strlen()
j = strlen(s) - 1;
จากนั้น เรากำลังสลับอักขระที่ตำแหน่ง i และ j ตัวแปร i จะเพิ่มขึ้นและ j จะลดลง
while (i < j) {
t = s[i];
s[i] = s[j];
s[j] = t;
i++;
j--;
}