-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?

iliketocode
  • 6,978
  • 5
  • 46
  • 60
Florin M.
  • 2,149
  • 3
  • 34
  • 92
  • 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

6

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);
}
iliketocode
  • 6,978
  • 5
  • 46
  • 60
Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306
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,378
  • 5
  • 32
  • 66
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
  • 27,818
  • 6
  • 51
  • 82