如何在 C 或 C++ 中就地反轉一個字串?


在本文中,我們將瞭解如何就地反轉一個字串。因此,我們不會使用其他記憶體空間進行反轉。在 C++ 中,我們可以使用 std::string。但對於 C,我們必須使用字元陣列。在本程式中,我們使用字元陣列獲取字串。然後進行反轉。

Input: A string “This is a string”
Output: The reversed string “gnirts a si sihT”

演算法

reverse_string(str)

輸入 − 字串

輸出 − 反轉後的字串。

len := the length of the string
i := 0 and j := (len-1)
while i < j, do
   swap the characters from position i and j
   i := i + 1
   j := j - 1
done

示例程式碼

 現場演示

#include <iostream>
#include<cstring>
using namespace std;
void reverse(char s[]) {
   int len = strlen(s) ; //get the length of the string
   int i, j;
   for (i = 0, j = len - 1; i < j; i++, j--) {
      swap(s[i], s[j]);
   }
}
int main() {
   char s[20] = "This is a string";
   cout << "Main String: " << s <<endl;
   reverse(s);
   cout << "Reversed String: " << s <<endl;
}

輸出

Main String: This is a string
Reversed String: gnirts a si sihT

更新於:2019-07-30

517 次瀏覽

開啟您的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.