转换为整数int数组的逗号分隔字符串 [英] Convert comma separated string of ints to int array
问题描述
我只找到一个办法做到这一点相反的方式轮:创造,而不是对如何输入转换如字符串str =1,2从一个int列表或数组分隔的字符串逗号, 3,4,5;
来int数组或列表
I only found a way to do it the opposite way round: create a comma separated string from an int list or array, but not on how to convert input like string str = "1,2,3,4,5";
to an array or list of ints.
下面是我实现的(由<一个启发href=\"http://stackoverflow.com/questions/1018407/what-is-the-most-elegant-way-to-get-a-set-of-items-by-index-from-a-collection/1018624#1018624\">this通过埃里克利珀后):
Here is my implementation (inspired by this post by Eric Lippert):
public static IEnumerable<int> StringToIntList(string str)
{
if (String.IsNullOrEmpty(str))
{
yield break;
}
var chunks = str.Split(',').AsEnumerable();
using (var rator = chunks.GetEnumerator())
{
while (rator.MoveNext())
{
int i = 0;
if (Int32.TryParse(rator.Current, out i))
{
yield return i;
}
else
{
continue;
}
}
}
}
你觉得这是一个很好的做法还是有一个更容易,甚至内置的方式?
Do you think this is a good approach or is there a more easy, maybe even built in way?
编辑:对不起任何混乱,但该方法需要处理像1,2 ,,, 3
或无效的输入###,5,
等,通过跳过它。
Sorry for any confusion, but the method needs to handle invalid input like "1,2,,,3"
or "###, 5,"
etc. by skipping it.
推荐答案
您应该使用foreach循环,像这样的:
You should use a foreach loop, like this:
public static IEnumerable<int> StringToIntList(string str) {
if (String.IsNullOrEmpty(str))
yield break;
foreach(var s in str.Split(',')) {
int num;
if (int.TryParse(s, out num))
yield return num;
}
}
请注意,喜欢你原来的职位,这将忽略不能解析的数字。
Note that like your original post, this will ignore numbers that couldn't be parsed.
如果你想抛出一个异常,如果一些无法解析,可以更简单地使用LINQ做到这一点:
If you want to throw an exception if a number couldn't be parsed, you can do it much more simply using LINQ:
return (str ?? "").Split(',').Select<string, int>(int.Parse);
这篇关于转换为整数int数组的逗号分隔字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!