反转字符串(迭代)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
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短