Reading in a text file is more "intelligent"

I have a text file that contains a list of alphabetically ordered variables with their variable numbers next to them, formatted as follows:

aabcdef           208
abcdefghijk       1191
bcdefga           7
cdefgab           12
defgab            100
efgabcd           999
fgabc             86
gabcdef           9
h                 11
ijk               80
...
...

I would like to read each text as a string and keep it marked with id # something like reading "aabcdef" and store it in an array at point 208.

The 2 problems I am facing are the following:

  • I have never read from a file in C #, is there a way to read, say, from the beginning of a line to a space as a line? and then the next line as an int to the end of the line?

  • , ( , 3000, 200 ). , , /// .. .

+4
2

, , Regex, ( , ) .

, , . .

, MatchCollection , , 3- - , - , !

StringBuilder builder = new StringBuilder();
builder.AppendLine("djdodjodo\t\t3893983");
builder.AppendLine("dddfddffd\t\t233");
builder.AppendLine("djdodjodo\t\t39838");
builder.AppendLine("djdodjodo\t\t12");
builder.AppendLine("djdodjodo\t\t444");
builder.AppendLine("djdodjodo\t\t5683");
builder.Append("djdodjodo\t\t33");

// Replace this line with calling File.ReadAllText to read a file!
string text = builder.ToString();

MatchCollection matches = Regex.Matches(text, @"([^\s^\t]+)(?:[\s\t])+([0-9]+)", RegexOptions.IgnoreCase | RegexOptions.Multiline);

// Here the magic: we convert an IEnumerable<Match> into a dictionary!
// Check that using regexps, int.Parse should never fail because
// it matched numbers only!
IDictionary<int, string> lines = matches.Cast<Match>()
                                    .ToDictionary(match => int.Parse(match.Groups[2].Value), match => match.Groups[1].Value);

// Now you can access your lines as follows:
string value = lines[33]; // <-- By value

:

, - , , , , , "[-]. [-]" ( : address.Name).

([\w\.]+)[\s\t]+([0-9]+), .

!;)

2:

, , ([^\s^\t]+)(?:[\s\t])+([0-9]+).

, - , .

3:

, .NET 3.0 ToDictionary .NET 3.5. .NET 3.0, ToDictionary(...) :

Dictionary<int, string> lines = new Dictionary<int, string>();

foreach(Match match in matches)
{
      lines.Add(int.Parse(match.Groups[2].Value), match.Groups[1].Value);
}
+1

Dictionary . File.ReadLines, \t (tab), :

var values = File.ReadLines("path")
    .Select(line => line.Split(new [] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries))
    .ToDictionary(parts => int.Parse(parts[1]), parts => parts[0]);

values[208] aabcdef. , :)

, , Dictionary , .

+5

Source: https://habr.com/ru/post/1542247/


All Articles