Phần này sẽ xem cách đảo ngược chuỗi rất nhanh dùng C++. Để đảo ngược, có hàm built-in trong thư viện algorithm, gọi là reverse(). Hàm này nhận con trỏ đầu và cuối của container, rồi đảo ngược các phần tử.
Input: Chuỗi "Hello World" Output: "dlroW olleH"
Thuật toán
Step 1: Nhận một chuỗi Step 2: Đảo ngược dùng reverse() Step 3: In kết quả. Step 4: Kết thúc
Ví dụ mã
#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;
// đảo ngược dùng reverse()
reverse(my_str.begin(), my_str.end());
cout << "Final state of this string: " << my_str;
}
Kết quả
Initial state of this string: This is a string to be reversed Final state of this string: desrever eb ot gnirts a si sihT