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

การกลับสตริง (Reverse String) ใน C/C++

ตัวอย่างโค้ด (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

อัลกอริธึม

  1. คำนวณความยาวสตริง j = strlen(s) - 1
  2. Swap ตัวอักษร s[i] และ s[j]
  3. 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> สะดวกและปลอดภัยกว่า