c# - 如何剪切字符串的第一部分并存储它
问题描述
我有一个 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);
推荐阅读
- java - JavaFX - 后台线程上的 javafx.beans.property 更新
- google-cloud-platform - 将设备从一个注册表复制到另一个 Google IoT Core
- android - 在 Android 7(root)上,libusb_init 失败并显示 LIBUSB_ERROR_OTHER
- swiftui - 在 SwiftUI 中更轻松或更紧凑地实现等待代码
- postgresql - postgresql 数据库的所有者
- testing - 找不到 appium ID,因为所有 ID 都显示为正方形
- python - Python函数月份范围
- r - ggplot - 使用箭头在末尾标记每一行
- google-apps-script - 在 Google 表格中创建顺序自动生成 ID 的公式
- ios - VStack中的SwiftUI不同的对齐文本