字符串阵列String[]转换为整型阵列Int[]
原始数据:
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 Ae { private string _InputValue; private char _Delimiter; public Ae(string inputValue, char delimiter) { this._InputValue = inputValue; this._Delimiter = delimiter; } }
public string[] StringToStringArray() { return _InputValue.Split(new char[] { _Delimiter }, StringSplitOptions.RemoveEmptyEntries); }
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) { // ... } } }
如果你的.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); }