将字符串数组转换为int [] [英] converting a string array to int[]

查看:102
本文介绍了将字符串数组转换为int []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的数组

string[]myNumber=new string[]{"1,2,5,4,6,"};



我如何将上述数组转换为:

int[]number=new int[]{1,2,5,4,6,};



请注意,我尝试使用myNumbers.CopyTo(number,0),但失败,并出现系统警告,两个数组必须具有相同的类型和大小.

还是我可以使用其他任何方式,例如List<>来实现此功能.

我的目的是将string数组转换为int[]

在此先感谢
您的马丁

解决方案

尝试

string[] myNumber=new string[]{"1,2,5,4,6,"};
string[] arr = String.Split(myNumber[0]);
int[] intarr = new intarr[arr.count];
foreach(string str in arr)
{
   intarr[count++] = Convert.ToInt(str);
}


public int[] StringToInt(string[] arr)
{
int i;
List<int> result = new List<int>();
for(int x=0;x < arr.Length; x++)
{
    if (int.TryParse(arr[x], out i))
        result.Add(i);
}
return result.ToArray();
}
</int></int>



万一解析了无效的字符串,这将稍微安全些. ,5"... ...不是五个单独的字符串. :)

但是...这是一种实现方法...

 字符串 [] strValues =  "   1"  2"  3 "  4"  5"};
 int  [] intValues = strValues.Select(val = >  Convert.ToInt32(val)).ToArray (); 


hi there,I have my array

string[]myNumber=new string[]{"1,2,5,4,6,"};



how can i convert above array to:

int[]number=new int[]{1,2,5,4,6,};



Note that i have tried to use myNumbers.CopyTo(number,0),it failed with a system warning that the two array must be of the same type and size.

Or is there any other way i can use, like List<> to achieve this function.

My aim is to convert the string array to int[]

Thanks in advance
Yours Martin

解决方案

Try

string[] myNumber=new string[]{"1,2,5,4,6,"};
string[] arr = String.Split(myNumber[0]);
int[] intarr = new intarr[arr.count];
foreach(string str in arr)
{
   intarr[count++] = Convert.ToInt(str);
}


public int[] StringToInt(string[] arr)
{
int i;
List<int> result = new List<int>();
for(int x=0;x < arr.Length; x++)
{
    if (int.TryParse(arr[x], out i))
        result.Add(i);
}
return result.ToArray();
}
</int></int>



This will be just a little safer in case an invalid string is parsed in.


First, the way you intialized your string array, you created one string of "1,2,3,4,5" ... not five individual strings. :)

But... here is one way to do it...

string[] strValues = new string[] { "1", "2", "3", "4", "5" };
int[] intValues = strValues.Select(val => Convert.ToInt32(val)).ToArray();


这篇关于将字符串数组转换为int []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆