ในส่วนนี้ เราจะดูวิธี reverse string อย่างรวดเร็วโดยใช้ C++ สำหรับการ reverse มี built-in function ใน algorithm library ชื่อ reverse() ฟังก์ชันนี้รับ beginning และ ending pointer ของ container แล้ว reverse elements
Input: A number string "Hello World" Output: "dlroW olleH"
Algorithm
Step 1: Take a string Step 2: Reverse it using reverse() function Step 3: Print the result. Step 4: End
ตัวอย่างโค้ด
#include<iostream>
#include<algorithm>
using namespace std;
main() {
string my_str = "This is a string to be reversed";
cout << "Initial state of this string: " << my_str << endl;
//reverse using the reverse() function for reversing a string
reverse(my_str.begin(), my_str.end());
cout << "Final state of this string: " << my_str;
}
ผลลัพธ์
Initial state of this string: This is a string to be reversed Final state of this string: desrever eb ot gnirts a si sihT