各路方法1、使用cstring中的strlen函数获取字符串长度,结合for反着循环。2、使用algorithm中的reverse函数。3、使用string.h中的strrev函数。4、数字翻转
(1),使用while循环。(2),使用to_string函数先将数字转字符串,在反着循环字符串。 总结:
显然,大家可以使用for循环反着循环一遍字符串。也就是小编下面提到的方法(1),但是这不是小编写这篇文章的目的。小编这里将介绍更多更加高效的方法来实现。
例如:string str1 = “abcd”,string str2 = "123"
处理后得到:str1 = “dcba”,str2 = "321"
### 比较容易想到,但是效率不高,且容易出错。
#include#include using namespace std; int main(){ char s[10]; cin>>s; int len=strlen(s); for(int i=len-1;i>=0;i--) cout< 2、使用algorithm中的reverse函数。### string类型字符建议使用#include3、使用string.h中的strrev函数。#include using namespace std; int main(){ string str; cin >> str; reverse(str.begin(), str.end()); cout << str << endl; return 0; } char类型字符建议使用#include#include using namespace std; int main(){ char s[10]; cin>>s; strrev(s); cout< 4、数字翻转 (1),使用while循环。#include#include using namespace std; int fac(int n) { int res = 0; while (n) { res = res * 10 + n % 10; n = n / 10; } return res; } int main(){ int x; cin>>x; int num=fac(x); cout< (2),使用to_string函数先将数字转字符串,在反着循环字符串。 #include#include using namespace std; int main(){ int num; cin>>num; string s=to_string(num); int len=s.length(); for(int i=len-1;i>=0;i--) cout< 注意:最后得到的是字符,要转化为数字,得进行转化,例如:
char s='2'; int num=(int)(s-'0'); cout<总结: 对于字符串类型,如果是string类型,建议使用方法2,如果是char类型,建议使用方法3;如果是数字类型,建议使用方法4里面的(2),比较不容易出错。
作者头像:
作者id:薇薇的憨宝



