Reputation: 167
I have a .txt file in my project which has the following contents:
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, e.g. 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. How do I do that using C#?
Upvotes: 1
Views: 2190
Reputation: 186688
Are you looking for Substring
and IndexOf
?
string[] values = lines
.Select(line => line.Substring(line.IndexOf(':') + 1).TrimLeft())
.ToArray();
If you want to preserve names (e.g. Mode
, score_2
etc.) try 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();
Upvotes: 1