我有一个 txt 文件,其中的行以一个随机字符开头,后跟 7 个数字,如下所示:
- A1234567 - 随机
- E2345678 - 随机
- D5423434 - 随机
我想从每一行中复制前 8 个字符并存储它们,以便制作一个只包含起始字符所需部分的 txt 文件。
我发现 Substring 方法可以工作,我只是不知道如何用它们制作数组。
如果有人能帮助我,那将对我有很大帮助。
谢谢!
最佳答案
查询时,尝试使用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);
关于c# - 如何剪切字符串的第一部分并存储它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51243278/