【问题标题】:Is this the best way in C# to convert a delimited string to an int array?这是 C# 中将分隔字符串转换为 int 数组的最佳方法吗?
【发布时间】:2009-04-28 12:52:00
【问题描述】:

给定下面的字符串:

string str = "1,2,3";

这是将其转换为 int 数组的最佳扩展吗?

static class StringExtensions
{
    public static int[] ToIntArray(this string s)
    {
        return ToIntArray(s, ',');
    }
    public static int[] ToIntArray(this string s, char separator)
    {
        string[] ar = s.Split(separator);
        List<int> ints = new List<int>();
        foreach (var item in ar)
        {
            int v;
            if (int.TryParse(item, out v))
                ints.Add(v);
        }
        return ints.ToArray();
    }
}

【问题讨论】:

    标签: c# string


    【解决方案1】:

    这真的取决于你想对非整数字符串做什么。此刻你默默地放下它们。就个人而言,我希望它出错。这也让你可以使用更简洁的:

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

    【讨论】:

      【解决方案2】:

      这种方法非常简洁,如果拆分字符串包含任何无法解析为 int 的值,则会抛出(信息量不大的)FormatException

      int[] ints = str.Split(',').Select(s => int.Parse(s)).ToArray();
      

      如果您只想静默删除任何非 int 值,您可以试试这个:

      private static int? AsNullableInt(string s)
      {
          int? asNullableInt = null;
      
          int asInt;
      
          if (int.TryParse(s, out asInt))
          {
              asNullableInt = asInt;
          }
      
          return asNullableInt;
      }
      
      // Example usage...
      int[] ints = str.Split(',')
          .Select(s => AsNullableInt(s))
          .Where(s => s.HasValue)
          .Select(s => s.Value)
          .ToArray();
      

      【讨论】:

        【解决方案3】:

        如果列表中的一个元素没有解析为 int,这将爆炸,这可能比静默失败要好:

        public static int[] ToIntArray(this string value, char separator)
        {
            return value.Split(separator).Select(i => int.Parse(i)).ToArray();
        }
        

        【讨论】:

          【解决方案4】:

          看起来不错,如果其中一项无法转换而不是静默失败,我也会抛出异常。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-09-09
            • 1970-01-01
            • 1970-01-01
            • 2023-03-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-21
            相关资源
            最近更新 更多