繁体   English   中英

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

[英]C# convert XML Node string to Int32

我从 web 服务读取数据并且不干净。 我需要将字符串转换为 Int,其中字符串可以是 null、数字或空格。 我制作了简单的程序来实现这一点,但我的代码没有命中空格...如果 (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 此处检查数据类型范围。

使用数据类型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;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM