Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a string line per line in C# [duplicate]

Tags:

string

c#

Possible Duplicate:
Easiest way to split a string on newlines in .net?

I'm trying to read out and interpret a string line per line. I took a look at the StringReader class, but I need to find out when I'm on the last line. Here's some pseudocode of what I'm trying to accomplish:

while (!stringReaderObject.atEndOfStream()) {
    interpret(stringReaderObject.readLine());
}

Does somebody know how to do this?

Thanks!

Yvan

like image 237
friedkiwi Avatar asked Oct 21 '10 16:10

friedkiwi


People also ask

How read a string from line in C#?

C# StringReader ReadLine The ReadLine method reads a line of characters from the current string and returns the data as a string. In the example, we count the lines of a multiline string. The ReadLine method returns the next line from the current string, or null if the end of the string is reached.

Does C go line by line?

Reading a file line by line is a trivial problem in many programming languages, but not in C. The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be.


1 Answers

If you are reading it in from a file, it is easier to do just do:

foreach(var myString in File.ReadAllLines(pathToFile))
    interpret(myString);

If you are getting the string from somewhere else (a web service class or the like) it is simpler to just split the string:

foreach(var myString in entireString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
    interpret(myString);
like image 56
Klaus Byskov Pedersen Avatar answered Oct 15 '22 01:10

Klaus Byskov Pedersen