把string转换成int型,非现有方法(非int.Parse)

    今天去面试了一家公司,之前做过类似的问题,过了很长时间,忘记怎么写了,所以今天在网上搜了一下,找到一个写的比较好的代码,保存下来。俗话说好记性不如烂笔头,还是写下来记忆比较深刻。

面试问题:把string转换成int型,非现有方法(非int.Parse)

解决方案:

using System;  
using System.Collections.Generic;  
using System.Text;  
namespace StringToInt  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            string strInput=string.Empty;  
            //输入e,E,退出操作  
            while (!strInput.Equals("e") || !strInput.Equals("E"))  
            {  
                strInput = Console.ReadLine();  
                int n = TransToInt(strInput);  
                if (n == -1)  
                {  
                    Console.WriteLine("输入的不是有效的数字字符或数字超出整形范围!");  
                }  
                else 
                {  
                    Console.WriteLine("转换后的整数是{0}", n);  
                }  
            }   
        }  
        private static int TransToInt(string str)  
        {  
            char[] ch = str.ToCharArray();//转换成char型来计算  
            int[] nArray = new int[str.Length];//定义一个int型数组  
            int nReturn = 0;   //定义返回的int型值  
            const int ten = 10;   //定义常量  
            for (int i = 0; i < ch.Length; i++)  
            {  
                if (ch[i] - 48 < 0 || ch[i] - 48>9)  //判断是否是可转换的int型  
                {  
                    return -1;  
                }  
                else 
                {  
                    nArray[i] = ch[i] - 48;  //把字符转换成int  
                    for (int j = ch.Length - i - 1; j > 0; j--)  
                    {  
                        nArray[i] *= ten;  
                    }  
                    nReturn += nArray[i];  
                }  
            }  
            if (!nReturn.ToString().Equals(str))//如果数字超出int型范围  
            {  
                return -1;  
            }  
            return nReturn;  
        }  
    }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值