反转字符串(迭代)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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短