Hello. I have the following problem: There is a text (suppose in text.txt) and in it a text of approximately the following content:

Blablabla 9f3 KKK 33 Pos 1 44 23 TextV "Вертикальность не помешает!" Up 15 

and I need to make it so that the second value is written to the variable, for example, 1 44 23 (from Pos) must be written to the position variable. I just tried to write my pathetic example, but ... after spending about an hour I didn’t think of anything (I just don’t know how to do it .. right now, I'll try again ..

 StreamReader streamReader = new StreamReader("name.txt"); string str = ""; string []strLine; int i; string NamePos = "Pos"; int []position; while (!streamReader.EndOfStream) { int i; i++; str += streamReader.ReadLine(); strLine[i] = str.Split(new char[i][]{' '}, StringSplitOptions.RemoveEmptyEntries); }//считали все слова и записали в массив streamReader.Close(); if(strcmp(strLine[i][j], NamePos)) //сравниваем с нужной нам строкой {i++}else{while(!strLine[i][j]) {position[j] = strLine[i][j]; j++}} // копируем 

something like that, but at over9000% sure that the code has billions of errors!

    1 answer 1

    Why so hard? C # is a very simple language.

     var splitChars = new[] { ' ' }; // разбивать будем по пробелу var result = File.ReadLines("name.txt") // прочитали все строки .Select(s => s.Split(splitChars, 2)) // поделили каждую на 2 части .Select(parts => parts.Skip(1).SingleOrDefault()) // выбрали вторую часть .Where(p => !string.IsNullOrWhiteSpace(p)) // отсеяли пустые строки .ToList(); // и сохранили в список 

    If you need to get a value by parameter name, it is better to do this:

     Dictionary<string, string> config; // ... public void ReadConfig(string filename) { config = File.ReadLines(filename) .Select(s => s.Split(splitChars, 2)) .Where(parts => parts.Any()) // убрали пустые строки .ToDictionary(parts => parts.First(), parts => parts.Skip(1).SingleOrDefault()); } 

    For the case of multiple values, you can do this:

     Dictionary<string, List<string>> config; // ... public void ReadConfig(string filename) { config = File.ReadLines(filename) .Select(s => s.Split(splitChars)) // убрали "2"! .Where(parts => parts.Any()) .ToDictionary(parts => parts.First(), parts => parts.Skip(1).ToList()); } 
    • @Timofffee: Well, for example: config ["Blablabla"] == "9f3", etc. - VladD
    • @Timofffee: As you wish. Now done so that everything is packaged in a single value. You can make the config["Blablabla"] an array of values. Now I will add the code. - VladD
    • @Timofffee: Maybe not there. Show the code. PS: the limit of comments ends, delete the top. - VladD
    • @Timofffee: "Error. This document is available only to its owner." - VladD