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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1763613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:36:22  来源:igfitidea点击:

Convert comma separated string of ints to int array

c#

提问by Max

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.

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

Here is my implementation (inspired by this post by Eric Lippert):

这是我的实现(受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?

你认为这是一个很好的方法还是有更简单的,甚至是内置的方法?

EDIT:Sorry for any confusion, but the method needs to handle invalid input like "1,2,,,3"or "###, 5,"etc. by skipping it.

编辑:对不起任何混乱,但该方法需要处理等无效的输入"1,2,,,3""###, 5,"通过跳过它等等。

采纳答案by SLaks

You should use a foreach loop, like this:

您应该使用 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;
    }
}

Note that like your original post, this will ignore numbers that couldn't be parsed.

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

If you want to throw an exception if a number couldn't be parsed, you can do it much more simply using LINQ:

如果您想在无法解析数字时抛出异常,您可以使用 LINQ 更简单地做到这一点:

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

回答by dcp

This is for longs, but you can modify it easily to work with ints.

这是 longs,但您可以轻松修改它以使用 ints。

private static long[] ConvertStringArrayToLongArray(string str)
{
    return str.Split(",".ToCharArray()).Select(x => long.Parse(x.ToString())).ToArray();
}

回答by mqp

I don't see why taking out the enumerator explicitly offers you any advantage over using a foreach. There's also no need to call AsEnumerableon chunks.

我不明白为什么去掉枚举器比使用foreach. 但也没有必要要求AsEnumerablechunks

回答by Jorge Córdoba

I think is good enough. It's clear, it lazy so it will be fast (except maybe the first case when you split the string).

我认为已经足够好了。很明显,它很懒,所以它会很快(除了第一种情况,当你拆分字符串时)。

回答by Jon Skeet

If you don't want to have the current error handling behaviour, it's really easy:

如果您不想拥有当前的错误处理行为,这真的很简单:

return text.Split(',').Select(x => int.Parse(x));

Otherwise, I'd use an extra helper method (as seen this morning!):

否则,我会使用额外的辅助方法(如今天早上所见!)

public static int? TryParseInt32(string text)
{
    int value;
    return int.TryParse(text, out value) ? value : (int?) null;
}

and:

和:

return text.Split(',').Select<string, int?>(TryParseInt32)
                      .Where(x => x.HasValue)
                      .Select(x => x.Value);

or if you don't want to use the method group conversion:

或者如果您不想使用方法组转换:

return text.Split(',').Select(t => t.TryParseInt32(t)
                      .Where(x => x.HasValue)
                      .Select(x => x.Value);

or in query expression form:

或以查询表达式形式:

return from t in text.Split(',')
       select TryParseInt32(t) into x
       where x.HasValue
       select x.Value;

回答by badbod99

This has been asked before. .Net has a built-in ConvertAll function for converting between an array of one type to an array of another type. You can combine this with Split to separate the string to an array of strings

以前有人问过这个问题。.Net 有一个内置的 ConvertAll 函数,用于在一种类型的数组和另一种类型的数组之间进行转换。您可以将其与 Split 结合使用以将字符串分隔为字符串数组

Example function:

示例函数:

 static int[] ToIntArray(this string value, char separator)
 {
     return Array.ConvertAll(value.Split(separator), s=>int.Parse(s));
 }

Taken from here

取自这里

回答by ZombieSheep

--EDIT-- It looks like I took his question heading too literally - he was asking for an array of ints rather than a List --EDIT ENDS--

--编辑--看起来我把他的问题标题写得太字面了-他要求的是一个整数数组而不是一个列表--EDIT ENDS--

Yet another helper method...

另一个辅助方法......

private static int[] StringToIntArray(string myNumbers)
{
    List<int> myIntegers = new List<int>();
    Array.ForEach(myNumbers.Split(",".ToCharArray()), s =>
    {
        int currentInt;
        if (Int32.TryParse(s, out currentInt))
            myIntegers.Add(currentInt);
    });
    return myIntegers.ToArray();
}

quick test code for it, too...

它的快速测试代码也是......

static void Main(string[] args)
{
    string myNumbers = "1,2,3,4,5";
    int[] myArray = StringToIntArray(myNumbers);
    Console.WriteLine(myArray.Sum().ToString()); // sum is 15.

    myNumbers = "1,2,3,4,5,6,bad";
    myArray = StringToIntArray(myNumbers);
    Console.WriteLine(myArray.Sum().ToString()); // sum is 21

    Console.ReadLine();
}

回答by McTrafik

Without using a lambda function and for valid inputs only, I think it's clearer to do this:

不使用 lambda 函数且仅用于有效输入,我认为这样做更清楚:

Array.ConvertAll<string, int>(value.Split(','), Convert.ToInt32);

回答by suizo

I have found a simple solution which worked for me.

我找到了一个对我有用的简单解决方案。

String.Join(",",str.Split(','));

String.Join(",",str.Split(','));

回答by Mohil Palav

import java.util.*;
import java.io.*;
public class problem
{
public static void main(String args[])enter code here
{
  String line;
  String[] lineVector;
  int n,m,i,j;
  Scanner sc = new Scanner(System.in);
  line = sc.nextLine();
  lineVector = line.split(",");
  //enter the size of the array
  n=Integer.parseInt(lineVector[0]);
  m=Integer.parseInt(lineVector[1]);
  int arr[][]= new int[n][m];
  //enter the array here
  System.out.println("Enter the array:");
  for(i=0;i<n;i++)
  {
  line = sc.nextLine();
  lineVector = line.split(",");
  for(j=0;j<m;j++)
  {
  arr[i][j] = Integer.parseInt(lineVector[j]);
  }
  }
  sc.close();
}
}

On the first line enter the size of the array separated by a comma. Then enter the values in the array separated by a comma.The result is stored in the array arr. e.g input:2,3 1,2,3 2,4,6 will store values asarr = {{1,2,3},{2,4,6}};

在第一行输入以逗号分隔的数组大小。然后输入以逗号分隔的数组中的值。结果存储在数组arr中。例如 input:2,3 1,2,3 2,4,6 将值存储为arr = {{1,2,3},{2,4,6}};