问题描述
我从网络服务读取数据并且不干净。我需要将字符串转换为 Int,其中字符串可以是空值、数字或带有空格。我制作了简单的程序来实现这一点,但是我的代码没有命中空格...如果 (uint.TryParse(cleanNumber,out ux)) 不确定我在拼图中遗漏了什么?
public class Program
{
static void Main(string[] args)
{
string no = "08709079777 ";
//string no = "0870777777";
Console.WriteLine("no "+ no);
Program o = new Program();
var t1 = o.ConvertStringToInt32(no);
Console.WriteLine("t1 "+ t1);
Console.ReadLine();
}
private int ConvertStringToInt32(string number)
{
int returnIntVal = 0;
try
{
if (!string.IsNullOrEmpty(number))
{
var cleanNumber = Regex.Replace(number,@"\s+","");
uint ux;
if (uint.TryParse(cleanNumber,out ux))
{
returnIntVal = (int)ux;
}
}
else
{
returnIntVal = 0;
}
}
catch(Exception exp)
{
var ex = exp;
}
return returnIntVal;
}
}
解决方法
您尝试解析的数字 0870777777
超出了 int 数据类型范围,即 -2,147,483,648
到 2,647
。检查 here 处的数据类型范围。
将数据类型用作 long
(或 Int64
)。
private static long ConvertStringToInt32(string number)
{
long returnIntVal = 0;
try
{
if (!string.IsNullOrEmpty(number))
{
var cleanNumber = Regex.Replace(number,@"\s+","");
if (long.TryParse(cleanNumber,out long ux))
{
returnIntVal = ux;
}
}
else
{
returnIntVal = 0;
}
}
catch(Exception exp)
{
var ex = exp;
}
Console.WriteLine("returnIntVal: " + returnIntVal);
return returnIntVal;
}
检查这个小提琴 - https://dotnetfiddle.net/3Luoon
,嗯,我不知道你为什么把事情复杂化,但这应该很容易解决
public int ConvertToInt(string n) {
// Trim should solve your case where the number end or start with whitespace. but just
// incase i did the replace thing to if there is any whitespace between the numbers.
// So its upp to you if you want to retaine the replace or not.
n = n?.Replace(" ","").Trim();
if (Int.TryParse(n,var out number))
return number;
else return 0;
}