如何在 C++ 中快速反轉一個字串?


在本部分,我們將瞭解如何使用 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

更新時間:2019-07-30

242 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.