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

7

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))  
{  
    .  
    .  
    .  
}  
Pundit answered 11/11, 2011 at 21:35 Comment(1)
What is wrong with "\r" (or, if you want a char, '\r')?Barrios
W
24
if (word.Contains(Environment.NewLine)) { }
Weinert answered 11/11, 2011 at 21:37 Comment(4)
No, that's "\r\n" on Windows.Achlamydeous
No, that's not the same. Environment.NewLine is usually (but not necessarily) a CRLF pair, i.e. char(13)+char(10).Girardo
That would be checking for OS specific NewLine in windows it's CRLF and on my mac it's LFUrethritis
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 :)Weinert
F
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)) { ... }
Franky answered 11/11, 2011 at 21:39 Comment(0)
Q
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)) 
{

}
Quarters answered 11/11, 2011 at 21:38 Comment(2)
It's even easier to read with: const char CR = '\r'; if(s.Contains(CR)) { ... }Biddable
@Olivier - yes, that's a bit easier on the eye :)Quarters
D
2

This is valid in all .NET versions:

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

This is valid only from .NET 3.5:

if (word.Contains('\r'))
{
  ...
}
Decorum answered 11/11, 2011 at 21:39 Comment(0)
G
1

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

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

should do the job.

Girardo answered 11/11, 2011 at 21:40 Comment(0)
U
1
s.Contains('\x0D');

characters are represent using single quotes;

What's wrong with using \r ?

Urethritis answered 11/11, 2011 at 21:51 Comment(0)
C
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;
}
Chantel answered 1/5, 2019 at 13:50 Comment(1)
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 mixStocking

© 2022 - 2024 — McMap. All rights reserved.