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