字符串阵列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; } }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 = ; 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
在控制台测试上面的方法:
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25