首页 > 解决方案 > 如果当前行以空格开头,则删除前面的 CRLF

问题描述

我需要使用文本文件的示例源:

Analysis: this is a test that wraps
 and this is the second line
 this is the third line
Demonstration: This is an example of only one line
Result data more text

如果一切正常,我的预期输出:

线路ID 资源 描述
1 分析:这是一个包装测试,这是第二行这是第三行
2 演示:这是一个只有一行的例子
3 结果数据更多文字

这是我要添加到 datagridview 的代码

string path = @"Sample1.txt";
dtSource.Columns.Add("LineID");
dtSource.Columns.Add("Source");
dtSource.Columns.Add("Description");
           
string[] readText = File.ReadAllLines(path);
int linenum = 0;
foreach (string s in readText)
{
    string sourceline = s;
    if(sourceline.StartsWith(" "))
    {
        sourceline = sourceline.Replace("\n", "").Replace("\r", ""); //STUCK
    }
    dtSource.Rows.Add(linenum, sourceline, "");
    linenum++;
}

dataGridView1.DataSource = dtSource;

现在我无法清楚地思考。正在考虑只使用List<string>then 操作,但不想添加更多东西。另外,考虑只修改前一个数据表行中的文本,将两者连接起来。任何 linq 查询或我可以做些什么来简化它?

标签: c#stringdatatable

解决方案


这应该工作

        foreach (string s in readText)
        {
            string sourceline = s;
            if (sourceline.StartsWith(" "))
            {
                dtSource.Rows[linenum - 1]["Source"] += sourceline;
            }
            else
            {
                dtSource.Rows.Add(linenum, sourceline, "");
                linenum++;
            }
        }

推荐阅读