ในส่วนนี้ เราจะมาดูวิธีการย้อนกลับสตริงอย่างรวดเร็วโดยใช้ C++ สำหรับการย้อนกลับมีฟังก์ชันในตัวในไลบรารีอัลกอริธึมที่เรียกว่า reverse() ฟังก์ชันนี้ใช้จุดเริ่มต้นและจุดสิ้นสุดของคอนเทนเนอร์ จากนั้นย้อนกลับองค์ประกอบ
Input: A number string “Hello World” Output: “dlroW olleH”
อัลกอริทึม
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