【问题标题】:C# DataTable String ManipulationC# DataTable 字符串操作
【发布时间】:2018-07-19 05:37:55
【问题描述】:

所以我使用 DataTable 和 for 循环使用 C# 中的 .split() 函数按空格/制表符分隔文件 将数据分成不同的列。

我遇到的问题是一些数据在我想保留为一列的文本之间有空格。

例如:

ID   Product        Form        Amount 
XXX  XXX            XXX, XXX    XXX

我遇到的问题是数据被拆分并使列正确,如下所示:

ID   Product        Form        Amount
XXX  XXX            XXX,        XXX     XXX

我想知道是否有一个要查看上一列并检查说逗号的情况 我想将上一列和当前列附加在一起。

除非有人有更好的方法,否则将其置于直接的上下文中:

我需要检查字符串(列)的最后一个字符。

然后我需要根据它是字母还是(逗号或括号)向数据表添加新列或 将一列附加到上一列...

这是我当前的拆分代码:

        Char[] seperator = new Char[] {'\t'};

        DataTable tbl = new DataTable(fileName);

        MessageBox.Show("There are: " + rows.Length + " rows.");

        if (rows.Length != 0 )
        {
            foreach (string headerCol in rows[0].Split(seperator))
            {
                tbl.Columns.Add(new DataColumn(headerCol));
            }
            if (tbl.Columns.Count <= 20)
            {
                for (int i = tbl.Columns.Count; i < 15; i++)
                {
                    tbl.Columns.Add("col " + i);
                }
            }
        }

        if (rows.Length > 1)
        {
            for (int rowIndex = 1; rowIndex < rows.Length; rowIndex++)
            {
                var newRow = tbl.NewRow();
                var cols = rows[rowIndex].Split(    );

                try
                {
                    //MessageBox.Show("Columns: " + cols.Length + " is fixed size: " + cols.IsFixedSize, "Column Data");

                        // If cannot find column then ignore and fill with blank...
                        for (int colIndex = 0; colIndex < cols.Length; colIndex++)
                        {
                            newRow[colIndex] = cols[colIndex];
                           // MessageBox.Show(cols[colIndex],"Col Index");
                        }

                }
                catch (Exception ex) {
                    //MessageBox.Show("Error: " + ex, "Error"); 
                } finally
                {

                }

                tbl.Rows.Add(newRow);
            }
        }

【问题讨论】:

  • 向我们展示拆分代码
  • 对列值执行 C# 字符串 Replace() 以删除空格
  • 如果列用制表符分隔,为什么用逗号或空格分隔?
  • 我从中提取的数据真的很乱,有很多空格和制表符我目前正在按制表符拆分列,但有些数据说(注射,100mg)或说(片剂(100mg )) 所以我想寻找逗号和括号,以便将数据的某些部分放在一列中。干杯,伙计们。
  • Ryan 我最后几次使用 Replace() 来删除导致问题的字符...非常感谢

标签: c# string datatable append character


【解决方案1】:

使用 Ryan 建议的 .Replace() 函数修复解决方案。

例如,我只是执行了很多次。 .替换(",\t", ",") .替换(", ", ",")

其中比预期更有效地修复了数据布局。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2012-10-20
    • 2012-09-26
    相关资源
    最近更新 更多