原始数据:
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 = 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
在控制台测试上面的方法: