今天听朋友说到个面试题:不用现有方法,把string转换成int型 就试着写了一下,没有考虑负数的情况,看的朋友可以自己试一下,也不难. 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; } } }