簡體   English   中英

如何剪切字符串的第一部分並將其存儲

[英]How to cut the first part of a string and store it

我有一個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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM