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

+3


source to share


4 answers


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.

+2


source


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", "");

      

+2


source


TrimEnd removes trailing characters, it does not "terminate" the string in the first instance of those characters. You need to search for the first instance of '\ r' or '\ n' and store the substring of characters before that.

0


source


Try the following:

string P = @"Copyright 1995-2010 BYTES.
        All rights Reserved.
        Formerly ""TheScripts.com"" from 2005-2008";

string firstLine = P.Split(
                       new string[] { System.Environment.NewLine },
                       StringSplitOptions.RemoveEmptyEntries)
                    .FirstOrDefault()

      

0


source







All Articles