字符串阵列String[]转换为整型阵列Int[]_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 字符串阵列String[]转换为整型阵列Int[]

字符串阵列String[]转换为整型阵列Int[]

 2017/12/6 17:36:09  Insus.NET  程序员俱乐部  我要评论(0)
  • 摘要:原始数据:stringinput="3,7,2,8,1,9,1,34,67,78,22";要处理为:string[]stringArray={"3","7","2","8","1","9","1","34","67","78","22"};最终处理为:int[]intArray={3,7,2,8,1,9,1,34,67,78,22};好吧,我们创建一个类:classAe{privatestring_InputValue;privatechar_Delimiter;publicAe
  • 标签: 字符串

原始数据:

string input = "3,7,2,8,1,9,1,34,67,78,22";


要处理为:

string[] stringArray = { "3", "7", "2", "8", "1", "9", "1", "34", "67", "78", "22" };


最终处理为:

int[] intArray = { 3, 7, 2, 8, 1, 9, 1, 34, 67, 78, 22 };


好吧,我们创建一个类:


class="code_img_closed" src="/Upload/Images/2017120617/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('b8d32543-e686-496f-878a-eaac330789de',event)" src="/Upload/Images/2017120617/2B1B950FA3DF188F.gif" alt="" />
 class Ae
    {
        private string _InputValue;
        private char _Delimiter;

        public Ae(string inputValue, char delimiter)
        {
            this._InputValue = inputValue;
            this._Delimiter = delimiter;
        }

    }
Source Code


在类中,添加一个方法,就是字符串转换为字符串阵列的方法:

 

 public string[] StringToStringArray()
        {
            return _InputValue.Split(new char[] { _Delimiter },
           StringSplitOptions.RemoveEmptyEntries);
        }
Source Code


最后创建另外一个方法,就是字符串阵列转换为整型阵列:

 

public void StringArrayToIntArray()
        {
            string[] stringArray = StringToStringArray();

            int length = stringArray.Length;
            int[] intArray = new int[length];

            for (int i = 0; i < length; i++)
            {
                try
                {
                    intArray[i] = Convert.ToInt32(stringArray[i]);
                }
                catch (Exception)
                {
                    // ...
                }
            }
        }
Source Code

 
如果你的.NET环境是3.0以上,有一个方法Array.ConvertAll<string, int>更加便捷:



 public void StringArrayToIntArray()
        {
            string[] stringArray = StringToStringArray();

            int length = stringArray.Length;
            int[] intArray = new int[length];           

            intArray = Array.ConvertAll<string, int>(stringArray, int.Parse);
        }
Source Code


在控制台测试上面的方法:


 

发表评论
用户名: 匿名