-2

I do want to get all the text before the first \r\n\ symbol. For example,

lalal lalal laldlasdaa daslda\r\n\Prefersaasda reanreainrea

I would need: lalal lalal laldlasdaa daslda. The above string can be empty, but it also may not contain any '\r\n\' symbol." How can I achieve this?

John Smith
  • 7,243
  • 6
  • 49
  • 61
Florin M.
  • 2,159
  • 4
  • 39
  • 97
  • 1
    Possible duplicate of [Easiest way to split a string on newlines in .NET?](http://stackoverflow.com/questions/1547476/easiest-way-to-split-a-string-on-newlines-in-net) – VinKel Jan 09 '17 at 08:17
  • 1
    Please note your input is not a valid string, their is an additional `\` after `\r\n` that make this input invalid – sujith karivelil Jan 09 '17 at 08:23
  • That is not a good duplicate since it has too much overhead compared to the answers given @VinKel – Patrick Hofman Jan 09 '17 at 08:33

3 Answers3

7

You can use IndexOf to get the position, then use Substring to get the first part:

string s = "lalal lalal laldlasdaa daslda\r\n Prefersaasda reanreainrea";

int positionOfNewLine = s.IndexOf("\r\n");

if (positionOfNewLine >= 0)
{
    string partBefore = s.Substring(0, positionOfNewLine);
}
John Smith
  • 7,243
  • 6
  • 49
  • 61
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
3

You can use Split like this

string mystring = @"lalal lalal laldlasdaa daslda\r\n\Prefersaasda reanreainrea";
string mylines = mystring.Split(new string[] { @"\r\n" }, StringSplitOptions.None)[0];

Screen Shot

Whereas if the string is like

string mystring = "lalal lalal laldlasdaa daslda\r\n Prefersaasda reanreainrea";
string mylines = mystring.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)[0];

Environment.NewLine will also work with it. The with \r\n\P is making that string an invalid string thus \r\n P makes it a new line

Mohit S
  • 13,723
  • 6
  • 34
  • 69
3

Hope that this is what you are looking for:

string inputStr = "lalal lalal laldlasdaa daslda\r\nPrefersaasda reanreainrea";
int newLineIndex =  inputStr.IndexOf("\r\n");
if(newLineIndex != -1)
{ 
  string outPutStr = inputStr.Substring(0, newLineIndex );
  // Continue
}
else
{
    // Display message no new line character 
}

Checkout an example here

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88