首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >包含记录之间回车文本文件

包含记录之间回车文本文件
EN

Stack Overflow用户
提问于 2018-11-30 00:30:13
回答 1查看 139关注 0票数 0

我有一个文本文件,其中包含独立格式的表格数据。在记录之间出现换行的行很少。有什么原因要解决这个问题吗

例如:

代码语言:javascript
复制
Date,S.No,Comments

2018-11-10,1,This is line one

2018-11-10,2,this is 

line two

2018-11-10,3,this is line 

three

在上面的第二行和第三行数据行的示例中,在到达行尾并创建新行之前发生了换行。

EN

回答 1

Stack Overflow用户

发布于 2018-11-30 03:04:20

这是我对你的问题的评论。

代码语言:javascript
复制
using System;
using System.Collections.Generic;

namespace _53543524_FileWithBrokenRecords
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> records = new List<string>();
            using (System.IO.StreamReader sr = new System.IO.StreamReader("M:\\StackOverflowQuestionsAndAnswers\\53543524_FileWithBrokenRecords\\sampledata.txt"))
            {
                string currentLine = string.Empty;
                bool headerline = true;
                System.Text.RegularExpressions.Regex newRecordSartRegex = new System.Text.RegularExpressions.Regex("^\\d{4}-\\d{2}-\\d{2},");
                while ((currentLine = sr.ReadLine()) != null)
                {
                    if (headerline)
                    {
                        //this handles the header record
                        records.Add(currentLine);
                        headerline = false;
                    }
                    else if (newRecordSartRegex.IsMatch(currentLine))
                    {
                        //this is a new record, so create a new entry in the list
                        records.Add(currentLine);
                    }
                    else
                    {
                        //this is the continuation on a ongoing record,
                        //so append to the last item in the list
                        if (!string.IsNullOrWhiteSpace(currentLine))
                        {
                            //add to the current record only if the line is not empty
                            records[records.Count - 1] += currentLine;
                        }
                    }
                }
            }

            foreach (string item in records)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
    }
}

结果是这样的:

代码语言:javascript
复制
Date,S.No,Comments
2018-11-10,1,This is line one
2018-11-10,2,this is line two
2018-11-10,3,this is line three
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53543524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档