【问题标题】:Convert 2D string array into 2D int array (Multidimensional Arrays)将 2D 字符串数组转换为 2D int 数组(多维数组)
【发布时间】:2017-04-04 04:02:33
【问题描述】:

我想替换string[,]二维数组

public static readonly string[,] first =
{
    {"2", " ", " ", " ", "1"},
    {"2", " ", "4", "3", " "},
    {" ", "2", " ", "1", " "},
    {" ", "1", " ", "3", " "},
    {"1", " ", " ", " ", " "}
};

进入int[,]数组

int X=-1;
public static readonly int[,] second =  
{
    {2, X, X, X, 1},
    {2, X, 4, 3, X},
    {X, 2, X, 1, X},
    {X, 1, X, 3, X},
    {1, X, X, X, X}
};

是否可以将string[,] 数组转换为int[,] 数组?如果是,如何将string[,] 转换为int[,]?谢谢。

【问题讨论】:

  • 我试图用循环解决这个问题,但我做不到,因为 X 应该是空字符串 ""
  • 那我不明白你想做什么。如果X 不是int,则不能将其放入int 数组中。

标签: c# arrays multidimensional-array type-conversion 2d


【解决方案1】:

现场示例: Ideone

public static readonly string[,] first =
{
     {"2", " ", " ", " ", "1"},
     {"2", " ", "4", "3", " "},
     {" ", "2", " ", "1", " "},
     {" ", "1", " ", "3", " "},
     {"1", " ", " ", " ", " "}
};

转换 (请注意,当字符串 = " " 时,我将使用 0 代替)

int[,] second = new int[first.GetLength(0), first.GetLength(1)];

for (int j = 0; j < first.GetLength(0); j++)    
{
    for (int i = 0; i < first.GetLength(1); i++)
    {
        int number;
        bool ok = int.TryParse(first[j, i], out number);
        if (ok)
        {
            second[j, i] = number;
        }
        else
        {
            second[j, i] = 0;
        }
    }
}

【讨论】:

    【解决方案2】:
    string[,] first =
    {
        {"2", " ", " ", " ", "1"},
        {"2", " ", "4", "3", " "},
        {" ", "2", " ", "1", " "},
        {" ", "1", " ", "3", " "},
        {"1", " ", " ", " ", " "}
    };
    
    
    int[,] second = new int[first.GetLength(0), first.GetLength(1)];
    int x = -1;
    for (int i = 0; i < first.GetLength(0); i++)
    {
        for (int j = 0; j < first.GetLength(1); j++)
        {
            second[i, j] = string.IsNullOrWhiteSpace(first[i, j]) ? x : Convert.ToInt32(first[i, j]);
        }
    }
    

    【讨论】:

      【解决方案3】:

      假设 X = -1:

      private static int[,] ConvertToIntArray(string[,] strArr)
      {
          int rowCount = strArr.GetLength(dimension: 0);
          int colCount = strArr.GetLength(dimension: 1);
      
          int[,] result = new int[rowCount, colCount];
          for (int r = 0; r < rowCount; r++)
          {
              for (int c = 0; c < colCount; c++)
              {
                  int value;
                  result[r, c] = int.TryParse(strArr[r, c], out value) ? value : -1;
              }
          }
          return result;
      }
      

      【讨论】:

        【解决方案4】:

        使用您正在使用的循环并将空字符串替换为空值,如果您要使用此数组,只需检查该值是否不为空。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-14
          • 1970-01-01
          • 2014-08-31
          • 2016-03-24
          • 2012-06-08
          • 2020-02-27
          相关资源
          最近更新 更多