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?
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.
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.
Solution 1streamReader. ReadToEnd(); // file is now at end of file line = new List<string>(); string lineS; while ((lineS = streamReader. ReadLine()) !=
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.
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;
}
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;
}
theString.Split("\n".ToCharArray())[64]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With