反转字符串(迭代)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();
//从两个开始交换字符
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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便