ต่อไปนี้คือตัวอย่างการสลับสตริง
ตัวอย่าง
#include<stdio.h>
#include <string.h>
int main() {
char st1[] = "My 1st string";
char st2[] = "My 2nd string";
char swap;
int i = 0;
while(st1[i] != '\0') {
swap = st1[i];
st1[i] = st2[i];
st2[i] = swap;
i++;
}
printf("After swapping s1 : %s\n", st1);
printf("After swapping s2 : %s\n", st2);
return 0;
} ผลลัพธ์
After swapping s1 : My 2nd string After swapping s2 : My 1st string
ในโปรแกรมข้างต้น จะมีการประกาศอาร์เรย์ของถ่านประเภท st1 และ st2 สองอาร์เรย์ ตัวแปร char 'swap' และตัวแปรจำนวนเต็ม i ได้รับการประกาศ ขณะที่วนรอบกำลังตรวจสอบว่า st1 ไม่เป็นโมฆะ ให้สลับค่าของ st1 และ st2
char st1[] = "My 1st string";
char st2[] = "My 2nd string";
char swap;
int i = 0;
while(st1[i] != '\0') {
swap = st1[i];
st1[i] = st2[i];
st2[i] = swap;
i++;
}