How to detect a carriage return in a line
Here's the problem. I am working on a project in WPF and C # with 4.0.net platform. I have a string that I got from a textbox with Accepts return = "true". The line looks like this
string P = @"Copyright 1995-2010 BYTES.
All rights Reserved.
Formerly "TheScripts.com" from 2005-2008";
Now I want to detect when a carriage return is encountered. So that I can shorten the line to "Copyright 1995-2010 BYTES". and remove all characters after receiving a carriage return.
I tried doing this
string ip = datarow[0].ToString();
string trimed= ip.TrimEnd(new char[] {'\r','\n'});
profileFNcb.Items.Add(trimed);
DOES NOT WORK PLEASE HELP COUPLES
source to share
Use string.Split
c Environment.NewLine
in to break a line into line breaks:
myString.Split(new [] {Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries)
The result is a string array containing each string.
To get the first line if the returned string[]
is in a variable lines
:
string firstLine = lines[0]; // firstLine = "Copyright 1995-2010 BYTES."
The reasons your solution doesn't work is TrimEnd
only remove characters from the end of the string, not the middle.
source to share
A: I misunderstood your question - this should help:
string onlyCopyright = P.Substring(0, P.IndexOf("\n"));
Or even better:
string onlyCopyright = P.Substring(0, P.IndexOf(Environment.NewLine));
Trim
only removes leading and trailing spaces. You want to replace:
string noNewLine = ip.Replace("\n", "").Replace("\r", "");
source to share