C# 将 XML 节点字符串转换为 Int32

C# convert XML Node string to Int32

我从网络服务中读取数据但不干净。我需要将字符串转换为 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,6482,147,483,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;
}

检查这个 fiddle - 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;

}