栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++如何实现字符串和数字的反转

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++如何实现字符串和数字的反转

C++如何实现数字和字符串的反转

各路方法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"

各路方法 1、使用cstring中的strlen函数获取字符串长度,结合for反着循环。
### 比较容易想到,但是效率不高,且容易出错。
#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类型字符建议使用
#include   
#include   
using namespace std;  

int main(){
    string str;
    cin >> str;
    reverse(str.begin(), str.end());
    cout << str << endl;
    return 0;
}
3、使用string.h中的strrev函数。
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:薇薇的憨宝

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/780219.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号