views:

214

answers:

7

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?

+2  A: 

If you have a string instance already, you can use String.Split to split each line and check if line 65 is available and if so use it.

If the content is in a file use File.ReadAllLines to get a string array and then do the same check mentioned before. This will work well for small files, if your file is big consider reading one line at a time.

using (var reader = new StreamReader(File.OpenRead("example.txt")))
{
    reader.ReadLine();
}
João Angelo
A: 

Other than taking advantage of a specific file structure and lower level file operations, I don't think theres any faster way than to read 64 lines, discard them and then read the 65th line and keep it. At each step, you can easily check if you've read the entire file.

IVlad
+8  A: 

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;
}
Dag
What about using Environment.Newline instead?
Dan Diplo
String.Split() only accepts char, and if you pass Environment.NewLine.ToCharArray() every other line will be empty (edit: in Windows, Unix will work fine)
Dag
@Dag: StringSplitOptions.RemoveEmptyEntries
Henk Holterman
@Henk: You're right - except when you have empty lines in the original text? I'm still stuck with .NET 2.0 and don't have such fancy options :-) Thanks for the info.
Dag
+2  A: 

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.

Hans Kesting
A: 

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

Alexander
prone to index-out-of-bounds error
Veer
It will return line 65, and you will get '\r' at the start of all returned lines in environments where Environment.NewLine is "\r\n" (Windows).
Dag
yes, I was quick on that answer. The general idea though is a working one. Except, it is kind of slow when it comes strings of thousands of lines.When it comes to new lines, it depends on the source of the string. If it's written only with \n, without \r, then it wouldn't work. The format of the string doesn't depend on the environment, does it?Regular expressions would do the job in this case, but slower.
Alexander
+2  A: 

What you can do is, split the string based on the newline character.

string[] strLines = yourString.split(Environment.NewLine);
if(strLines.Length > lineNumber)
{
    return strLines[lineNumber];
}
KhanS
+1  A: 
Paul Ruane