How do I find whether a string has a carriage return by using the String.Contain function using its ascii character?

47,213

Solution 1

Since you state that you don't want to use \r then you can cast the integer to a char:

if (word.Contains((char)13)) { ... }

Solution 2

if (word.Contains(Environment.NewLine)) { }

Solution 3

You can enter a char value using single quotes

var s = "hello\r";

if (s.Contains('\r')) 
{

}

If it's easier to read, you can cast 13 to char

var s = "hello\r";

if (s.Contains((char)13)) 
{

}

Solution 4

I'm sure you can do this with a regular expression, but if you're dumb like me, this extension method is a good way to go:

public static bool HasLineBreaks(this string expression)
{
    return expression.Split(new[] { "\r\n", "\r", "\n" },StringSplitOptions.None).Length > 1;
}

Solution 5

Convert.Char(byte asciiValue) creates a char from any integer; so

if (word.Contains(Convert.Char(13)) 

should do the job.

Share:
47,213
C N
Author by

C N

Updated on May 02, 2020

Comments

  • C N
    C N about 4 years

    In C#, how do I find whether a string has a carriage return by using the String.Contains function? The ascii for carriage return is 13.

    Chr(13) is how a carriage return is represented in Visual Basic. How is a carriage return represented in C# using its ascii character and not "\r"?

    if (word.Contains(Chr(13))  
    {  
        .  
        .  
        .  
    }  
    
  • user1703401
    user1703401 over 12 years
    No, that's "\r\n" on Windows.
  • Jeremy McGee
    Jeremy McGee over 12 years
    No, that's not the same. Environment.NewLine is usually (but not necessarily) a CRLF pair, i.e. char(13)+char(10).
  • Olivier Jacot-Descombes
    Olivier Jacot-Descombes over 12 years
    It's even easier to read with: const char CR = '\r'; if(s.Contains(CR)) { ... }
  • James Kyburz
    James Kyburz over 12 years
    That would be checking for OS specific NewLine in windows it's CRLF and on my mac it's LF
  • Russ Cam
    Russ Cam over 12 years
    @Olivier - yes, that's a bit easier on the eye :)
  • Joao
    Joao about 7 years
    TBH I answered this way because I'm under the impression it's what the OP should hear more than the answer he wanted to hear. Either way he now has both answers :)