16

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))  
{  
    .  
    .  
    .  
}  
Ghasem
  • 14,455
  • 21
  • 138
  • 171
C N
  • 429
  • 5
  • 9
  • 15

7 Answers7

24
if (word.Contains(Environment.NewLine)) { }
Joao
  • 7,366
  • 4
  • 32
  • 48
19

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)) { ... }
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
5

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)) 
{

}
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
2

This is valid in all .NET versions:

if (word.Contains("\r"))
{
  ...
}

This is valid only from .NET 3.5:

if (word.Contains('\r'))
{
  ...
}
1

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;
}
Mike Bruno
  • 600
  • 2
  • 9
  • 26
  • Even though this works it's not optimal considering that it involves unnecessary string allocations. Having said that, for the sake of competeness I would also add the arcane "\f" (line feed) in the mix – XDS Aug 21 '23 at 14:58
1

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

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

should do the job.

Jeremy McGee
  • 24,842
  • 10
  • 63
  • 95
1
s.Contains('\x0D');

characters are represent using single quotes;

What's wrong with using \r ?

James Kyburz
  • 13,775
  • 1
  • 32
  • 33