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

ฟังก์ชัน C สำหรับสลับสตริง (Swap Strings)

การสลับสตริงใน C สามารถทำได้โดยการสลับตัวอักษรทีละตัว (Character-by-character) เนื่องจาก C ไม่มี String Type ในตัว ใช้ Char Array แทน

ตัวอย่าง: สลับสตริงด้วยลูป While

#include <stdio.h>
#include <string.h>

int main() {
    char st1[] = "My 1st string";
    char st2[] = "My 2nd string";
    char swap;
    int i = 0;
    
    // สลับตัวอักษรทีละตัว จนกว่าจะเจอ Null Terminator ของ st1
    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

คำอธิบาย

  1. ประกาศ st1 และ st2 เป็น Char Arrays ที่มีขนาดพอดีกับสตริง + Null Terminator
  2. char swap - ตัวแปรชั่วคราวสำหรับเก็บตัวอักษรขณะสลับ
  3. while(st1[i] != '\0') - ลูปจนกว่าจะถึงจบสตริง st1
  4. สลับ st1[i] และ st2[i] ทีละตัว

ข้อจำกัดของวิธีนี้

  • ขนาดอาร์เรย์ต้องเท่ากันหรือ st2 ใหญ่กว่า/เท่า st1 - มิฉะนั้น Buffer Overflow
  • สลับได้แค่ความยาวของ st1 - หาก st2 ยาวกว่า ส่วนท้ายจะไม่ถูกสลับ
  • ไม่สามารถใช้กับ String Literals (Read-only Memory) ได้

วิธีที่ดีกว่า: สลับ Pointers (สำหรับ Dynamic Strings)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void swapStrings(char **s1, char **s2) {
    char *temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}

int main() {
    char *str1 = strdup("My 1st string");
    char *str2 = strdup("My 2nd string");
    
    printf("Before: s1=%s, s2=%s\n", str1, str2);
    swapStrings(&str1, &str2);
    printf("After:  s1=%s, s2=%s\n", str1, str2);
    
    free(str1);
    free(str2);
    return 0;
}

ผลลัพธ์

Before: s1=My 1st string, s2=My 2nd string
After:  s1=My 2nd string, s2=My 1st string

ใน C++: ใช้ std::string และ std::swap

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string s1 = "My 1st string";
    std::string s2 = "My 2nd string";
    
    std::cout << "Before: s1=" << s1 << ", s2=" << s2 << "\n";
    std::swap(s1, s2);  // หรือ s1.swap(s2);
    std::cout << "After:  s1=" << s1 << ", s2=" << s2 << "\n";
    
    return 0;
}

สรุป

วิธีเหมาะสำหรับข้อควรระวัง
Character-by-character (ลูป)Fixed-size Char Arrays ขนาดเท่ากันBuffer Overflow Risk, ไม่สลับครบถ้าความยาวต่างกัน
Swap PointersDynamic Strings (malloc/strdup)ต้องจัดการ Memory เอง (free)
std::string + std::swapC++ (แนะนำ)ปลอดภัย เร็ว จัดการ Memory อัตโนมัติ