用 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 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.