简体   繁体   English

在C#中从文本文件中提取特定数据

[英]extracting specific data from text file in c#

I have a .txt file in my project which has the following contents: 我的项目中有一个.txt文件,其内容如下:

Mode: 1
Number of candidates: 64
serial number: 111111101
room number: 111111111
score_1: 0
score_2: 0
Total: 0

I read all the lines and store it in an array using the following. 我阅读了所有内容,并使用以下内容将其存储在数组中。

string[] lines = File.ReadAllLines("file.txt", Encoding.UTF8);

I want to extract only the values of each line, eg for the line with the "room number", I want to extract only "111111111" without the space and print it on console and save it in a variable. 我只想提取每行的值,例如,对于带有“房间号”的行,我只想提取不带空格的"111111111" ,并在控制台上打印并将其保存在变量中。 How do I do that using C#? 如何使用C#做到这一点?

Are you looking for Substring and IndexOf ? 您在寻找SubstringIndexOf吗?

 string[] values = lines
   .Select(line => line.Substring(line.IndexOf(':') + 1).TrimLeft())
   .ToArray();

If you want to preserve names (eg Mode , score_2 etc.) try Split : 如果要保留名称 (例如Modescore_2等),请尝试Split

 KeyValuePair<string, string>[] data = lines
   .Select(line => line.Split(new char[] {':'}, 2))
   .Where(items => items.Length >= 2) // let's filter out lines without colon
   .Select(items => new KeyValuePair<string, string>(items[0], items[1].TrimLeft()))
   .ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM