How to get specific line from a string in C#?
I have a string in C# and would like to get text fr开发者_StackOverflow社区om specific line, say 65. And if file does not have so many lines I would like to get "". How to do this?
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;
}
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;
}
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 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();
}
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];
}
theString.Split("\n".ToCharArray())[64]
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.
精彩评论