在本教程中,我们将讨论一个程序,以了解在C / C ++中反转字符串的不同方法。
用户定义的reverse()函数-
#include <bits/stdc++.h>
using namespace std;
//function to reverse given string
void reverse_str(string& str){
int n = str.length();
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
int main(){
string str = "nhooo";
reverse_str(str);
cout << str;
return 0;
}使用内置的reverse()函数-
#include <bits/stdc++.h>
using namespace std;
int main(){
string str = "nhooo";
reverse(str.begin(), str.end());
cout << str;
return 0;
}给定字符串的反向打印-
#include <bits/stdc++.h>
using namespace std;
void reverse(string str){
for (int i=str.length()-1; i>=0; i--)
cout << str[i];
}
int main(void){
string s = "nhooo";
reverse(s);
return (0);
}输出结果
tniopslairotut