Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get specific line from a string in C#?

I have a string in C# and would like to get text from specific line, say 65. And if file does not have so many lines I would like to get "". How to do this?

like image 726
Tom Smykowski Avatar asked Apr 09 '10 09:04

Tom Smykowski


People also ask

How do you get a specific line in a file in C?

You can use fgets [^] in a loop to read a file line by line. When no more lines can be read, it will return NULL. On the first line you can use sscanf[^] to extract the integer.

How do I read nth line of a file in C using file handling?

so, you can read every line by calling 'fgets' and keep counting the line number, when the line number not reach n ( less than n), discard the line content. when you reach nth line, stop reading and return the line content.

How do I read a line from a text file in C#?

Solution 1streamReader. ReadToEnd(); // file is now at end of file line = new List<string>(); string lineS; while ((lineS = streamReader. ReadLine()) !=

How do I read a specific line in a file in R?

Read Lines from a File in R Programming – readLines() Function. readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines.


4 Answers

private static string ReadLine(string text, int lineNumber)
{
    var reader = new StringReader(text);

    string line;
    int currentLineNumber = 0;

    do
    {
        currentLineNumber += 1;
        line = reader.ReadLine();
    }
    while (line != null && currentLineNumber < lineNumber);

    return (currentLineNumber == lineNumber) ? line :
                                               string.Empty;
}
like image 197
Paul Ruane Avatar answered Sep 22 '22 21:09

Paul Ruane


Quick and easy, assuming \r\n or \n is your newline sequence

string GetLine(string text, int lineNo)
{
  string[] lines = text.Replace("\r","").Split('\n');
  return lines.Length >= lineNo ? lines[lineNo-1] : null;
}
like image 20
EventHorizon Avatar answered Sep 21 '22 21:09

EventHorizon


theString.Split("\n".ToCharArray())[64]

like image 40
Alex Avatar answered Sep 25 '22 21:09

Alex


You could use a System.IO.StringReader over your string. Then you could use ReadLine() until you arrived at the line you wanted or ran out of string.

As all lines could have a different length, there is no shortcut to jump directly to line 65.

When you Split() a string you duplicate it, which would also double the memory consumption.

like image 37
Hans Kesting Avatar answered Sep 22 '22 21:09

Hans Kesting