用 C++ 反轉字串(迭代)


用 C++ 程式碼反轉字串有很多已定義的方法,包括棧、就地和迭代。在此示例中,將使用以下演算法以迭代方式反轉一個簡單的字串;

演算法

START
   Step-1: Input the string
   Step-2: Get the length of the string using length() method
   Step-3: Swap the last character to first using for loop
   Step-4: Print
END

為了避免上述計算的不相容性,用 C++ 語言編寫的程式碼進行了如下嘗試;

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
void strReverse(string& str){
   int n = str.length();
   // Swap character starting from two
   cout<<"interative reverse (Tomhanks)::";
   for (int i = 0; i < n / 2; i++)
      swap(str[i], str[n - i - 1]);
}
int main(){
   string str = "Tomhanks";
   strReverse(str);
   cout << str;
   return 0;
}

輸出

對上述程式碼進行編譯後,給定的字串“Tomhanks”將以反向順序列印如下所示;

Iterative reverse (Tomhanks):: sknahmoT

更新日期:2019 年 12 月 23 日

306 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告