class Program
{
static void Main(string[] args)
{
int result = StrConverter.Convert("123.45");
Console.WriteLine(result);
try
{
double t1 = int.MaxValue;
t1 = t1 + 1;
int max = StrConverter.Convert(t1.ToString());
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
}
Console.Read();
}}
/// <summary>
/// 转换类
/// </summary>
public class StrConverter
{
/// <summary>
/// 将形如 123.45 这样的字符串,转化为 123 这样的整型数
/// </summary>
/// <param name="src"></param>
/// <returns></returns>
public static Int32 Convert(string src)
{
if (string.IsNullOrEmpty(src))
{
throw new Exception("不可为空");
}
bool positive = true;
Int32 result = 0;
double tempResult = 0;
int start = 0;
while (start <= src.Length - 1 && src[start] == ' ')
{
if (start == Int16.MaxValue)
{
throw new Exception("空格太多" + start);
}
start++;
}
if (start <= src.Length - 1 && src[start] == '-')
{
positive = false;
start++;
}
for (int i = start; i < src.Length; i++)
{
int charInt = FromChar2Int(src[i]);
if (IsNumber(src[i]))
{
tempResult = tempResult * 10 + charInt;
result = result * 10 + charInt;
}
else if (src[i] == '.')
{
break;
}
else
{
throw new Exception("非法字符.位置" + i + " " + src[i]);
}
if (positive)
{
if (tempResult > ((double)Int32.MaxValue - 1))
{
throw new Exception("超出整形范围,太大了");
}
}
else
{
if (tempResult > ((double)Int32.MaxValue + 1))
{
throw new Exception("超出整形范围,太小了");
}
}
}
if (positive)
{
return result;
}
else
{
return -1 * result;
}
}
static bool IsNumber(char c)
{
int code = (int)c - 48;
if (code > 9 || code < 0)
{
return false;
}
return true;
}
static Int32 FromChar2Int(char c)
{
int code = (int)c - (int)'0';
return code;
}
}