gpt4 book ai didi

c# - 将逗号分隔的整数字符串转换为整数数组

转载 作者:IT王子 更新时间:2023-10-29 03:49:08 26 4
gpt4 key购买 nike

我只找到了一种相反的方法:从 int 列表或数组创建一个逗号分隔的字符串,但没有像 string str = "1,2,3,4 这样转换输入,5"; 到数组或整数列表。

这是我的实现(灵感来自 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;
}
}
}
}

您认为这是一种好方法还是有更简单甚至内置的方法?

编辑:对于任何混淆,我们深表歉意,但该方法需要处理无效输入,例如 "1,2,,,3""### , 5," 等跳过它。

最佳答案

您应该使用 foreach 循环,如下所示:

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;
}
}

请注意,与您的原始帖子一样,这将忽略无法解析的数字。

如果您想在无法解析数字时抛出异常,可以使用 LINQ 更简单地完成:

return (str ?? "").Split(',').Select<string, int>(int.Parse);

关于c# - 将逗号分隔的整数字符串转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1763613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com