C# 字符串转换成整数

csdn的一个题目,看了这篇文章后,就写了个C#的实现方式。

实现StrToInt方法,以下是代码:

        /// <summary>
        /// 将字符串转化为整数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static int StrToInt(string str)
        {
            long value = 0;
            if (string.IsNullOrEmpty(str))
            {
                return (int)value;
            }

            bool isNagetive = false;
            char[] ch = str.ToCharArray();

            int i = 0;

            while (i < ch.Length && ch[i] == ' ')
                i++;

            if (i < ch.Length && (ch[i] == '-' || ch[i] == '+'))
            {
                if (ch[i] == '-')
                {
                    isNagetive = true;
                }
                i++;
            }

            while (i < ch.Length)
            {
                if (ch[i]<'0'||ch[i]>'9')
                {
                    break;
                }
                
                if (isNagetive)
                {
                    value = value * 10 - (ch[i] - '0');
                    value = value < int.MinValue ? int.MinValue : value; //溢出处理
                }
                else
                {
                    value = value * 10 + (ch[i] - '0');
                    value = value > int.MaxValue ? int.MaxValue : value; //溢出处理
                }
                    

                i++;
                
            }

            return (int)value;
        }
原文地址:https://www.cnblogs.com/kangs/p/3129123.html