I parse the text file. You need to set the condition: "if the line starts with a number" and so on. How to implement it
2 answers
There is such a thing as String.StartWith(s1, s2) ; Where s1 string you are checking, and s2 is a substring whose presence is checked at the beginning
We have the following code:
StreamReader sr = new StreamReader(@puth); string buffer; // буфер для считывания строк while(!sr.EndOfStream) { buffer = sr.ReadLine(); if (String.StartWith(buffer, i.ToString()) // где і - нужное число, преобразованое в строку { // выполняешь нужные действия } } sr.Close(); You can also create a method that will perform the desired action depending on the containing number at the beginning of the read line, for example:
public static string DoSomeOperationWithString(string s, string subS) { string result; if(subS == "1.1") { // выполняешь действия, записывая результат в переменную result, потом возвращаешь ее } else if(subS == "1.2") { // выполняешь действия, записывая результат в переменную result, потом возвращаешь ее } return result; } You call the method in the body of the read cycle, instead of if , and the check is performed directly in the method. You can also create submethods that will be called from this method. I hope I checked your question.
In general, the answer to your question is here: https://msdn.microsoft.com/ru-ru/library/baketfxw(v=vs.110).aspx
PS: my first response to StackOverFlow :)
- oneAnd why at you
srnot inusing? If an exception happens inside, the file will remain open. - VladD - And so in general with the initiative :) - VladD
- The
StartsWithmethodStartsWithnot static. The given code is not combined. It would be good to fix it. - Alexander Petrov - Instead of String.StartWith (text, param) write someText.StartWith (param), where someText is the string to be checked and param is the test substring. And yes, I missed a little about using - Swoker
The answer is found! Implemented with Regex (regular expressions):
string line = sr.ReadLine(); RegexOptions ignoreCase = RegexOptions.IgnorePatternWhitespace; Regex reg = new Regex(@"^\s+[0-9]", ignoreCase); Match m = reg.Match(line);
StreamReader"? Make a detailed description of the question. - VladD