Finding where the newline is in the line:

I see that using the Visual Studio Object Viewer, my line is:

"_profileIconId = 5\n elo" 

What do I need to get text from start to new line.

Here is what I tried, but the IndexOf () method returns -1, which means that a new line was not found.

 var stringEx = "_profileIconId = 5\n elo"; var x = stringEx.IndexOf(Environment.NewLine); stat.Name = tempName.Substring(0,x); 

Any ideas on how to do this?

+6
string c #
source share
4 answers

This is because Environment.NewLine represents \r\n (carriage return + line), whereas you only have a line in the original line. Change the second line as follows:

 var x = stringEx.IndexOf("\n"); 
+12
source share

If you just want the first line of the line, you can do this:

 static string GetFirstLine(string text) { using (var reader = new StringReader(text)) { return reader.ReadLine(); } } 

The StringReader class deals with various line break scripts for you. From the MSDN documentation :

A line is defined as a sequence of characters followed by a line ("\ n"), carriage return ("\ r"), or carriage return immediately along the line ("\ r \ n").

Of course, if you don't want the overhead of creating a new StringReader object (although I doubt it is big), you can implement something similar to yourself:

 static string GetFirstLine(string text) { int? newlinePos = GetIndex(text, "\r") ?? GetIndex(text, "\n"); if (newlinePos.HasValue) { return text.Substring(0, newlinePos.Value); } return text; } // Not really necessary -- just a convenience method. static int? GetIndex(string text, string substr) { int index = text.IndexOf(substr); return index >= 0 ? (int?)index : null; } 
+5
source share

If you are running on a Windows platform, Environment.NewLine will search for "\ r \ n".

Try searching instead of \ n:

 var x = stringEx.IndexOf("\n"); 
+1
source share

Here is a general way to do this, which will remove the new line and everything after it from the line, but only when a new line exists in the line:

 int x = stringEx.IndexOf("\n"); if (x > 0) { stringEx= stringEx.Remove(x); } 
0
source share

All Articles