首页 > 解决方案 > 如何剪切字符串的第一部分并存储它

问题描述

我有一个 txt 文件,其中的行以随机字符开头,后跟 7 个数字,如下所示:

我想从每一行复制前 8 个字符并将它们存储起来,以便制作一个仅包含起始文件所需部分的 txt 文件。

我发现 Substring 方法可以工作,我只是不知道如何用它们制作一个数组。

如果有人可以帮助我,那将对我有很大帮助。

谢谢!

标签: c#.net

解决方案


查询时,尝试使用Linq

 using System.IO;
 using System.Linq;

 ...

 string[] result = File
   .ReadLines(@"c:\MyFile.txt")
 //.Where(line => line.Length >= 8) // uncomment if you want to remove short lines
   .Select(line => line.Length >= 8 
      ? line.Substring(0, 8) 
      : line)
   .ToArray();

如果您想确保该行以模式开头(大写字母后跟 7 位数字),您可以尝试正则表达式

  using System.IO;
  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  string[] result = File
    .ReadLines(@"c:\MyFile.txt")
    .Select(line => Regex.Match(line, "^[A-Z][0-9]{7}"))
    .Where(match => match.Success)
    .Select(match => match.Value)
    .ToArray();

要将日期写入文件,请使用File.WriteAllLines

  File.WriteAllLines(@"c:\cleared.txt", result); 

推荐阅读