【问题标题】:Creating a multidimensional array from a string with delimiter从带分隔符的字符串创建多维数组
【发布时间】:2018-11-15 19:09:38
【问题描述】:

我有一个这样的逗号分隔字符串:

string myString = "1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,#";

这基本上是我使用阅读器从文件中读取的 csv 文件中的数据。

在上面的字符串中,','代表数据分隔符,而'#'代表文件的EOL。

myString = myString.TrimEnd('#'); //Removing extra # in the end.
//Result of above 1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,

我想把上面的转换成多维数组,循环读取每一行数据的值并创建我自己的json。

所以我从下面的代码开始。这将导致我的行数和列数。

int rowCount = result.TrimEnd('#').Split('#').Count();
int colCount = result.TrimEnd('#').Split('#')[0].TrimEnd(',').Split(',').Length;

//Defining my object which I want to fill.
JObject myObject = new JObject();

下面我要循环遍历行和列,从每一行和每一列获取数据值

for (int row = o ; row <= rowCount; row++)
{
    for (int col = 0; col <= colCount; col++)
    {
       //So here I want to do something like:
       var rowValue = multiArray[row][col];

       //After getting the row value below is the logic to add to my object
       if(col == 0)
       {
            myObject.Add("first", rowValue);    
       }
       else if(col == colCount)
       {
            myObject.Add("last", rowValue);
       }
       else
       {
            myObject.Add(col, rowValue);
       }
    }
}

所以我的问题是如何在我的代码中创建多维数组“multiArray”。

我的 json 示例:

{
  "first": 1
  "1": a,
  "2": b,
  "last": C1
},
{
  "first": 2
  "1": c,
  "2": d,
  "last": C2
}

【问题讨论】:

  • 在给定起始字符串 "1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,#"
  • 那么你卡在哪里了?
  • @MattBurland 我最终的 json 将取决于文件的行和列,即字符串。我会负责创建 json,只是我不知道在上面的代码中创建多数组“multiArray”,我可以从中循环。我已经用 json 更新了我的帖子。
  • @OleEHDufour 正如我的帖子中提到的,我不知道如何创建“多数组”以便循环遍历它。
  • @user1563677 - 你有一个示例输入,示例输出是什么?

标签: c#


【解决方案1】:

以下代码创建并填充您的多维数组,但您的数据存在问题。由于额外的逗号,您的 json 看起来不像您的示例 json。

string myString = "1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,#".TrimEnd('#');

var rows = myString.Split('#');
var rowCount = rows.Length;
var columnCount = rows[0].Split(',').Length;

string[,] multiArray = new string[rowCount, columnCount];

for (int i = 0; i < rowCount; i ++)
{
    var values = rows[i].Split(',');
    for (int j = 0; j < columnCount && j < values.Length; j++)
    {
        multiArray[i,j] = values[j];
    }
}

我从中得到的结果是有一个 4x6 数组,每行只有 4 个值。

【讨论】:

  • 感谢会检查并回复
  • 我不得不对我的代码进行一些调整,但这工作正常。
猜你喜欢
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多