Irgat
Irgat

Reputation: 71

String compare in C#

I have a string like 20090101 and I want to compare it with ????01??.

if (input == "----01--") { .... }

How can I compare the 5th and 6th characters with "01"?

Upvotes: 0

Views: 879

Answers (5)

vittore
vittore

Reputation: 17579

As Bauer said you can use String functions, also you can convert string to Char Array and work with it char by char

Upvotes: 0

user287107
user287107

Reputation: 9418

you should create a regex expression. to check if the 4th and 5th byte is 01, you can write

var r = new Regex("^.{4}01$");
if(r.Match(str) ...) ... 

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 837906

Update: After seeing your comment I think you should parse the string as a DateTime:

string s = "20090101";
DateTime dateTime;
if (DateTime.TryParseExact(s, "yyyyMMdd", null, DateTimeStyles.None, out dateTime))
{
    if (dateTime.Month == 1)
    {
        // OK.
    }
}
else
{
    // Error: Not a valid date.
}

Upvotes: 11

Zach Johnson
Zach Johnson

Reputation: 24212

I think this may be what you want:

if (input.Substring(4, 2) == "01")
{
    // do something
}

This will get a two character substring of input (starting at character 5) and compare it to "01".

Upvotes: 5

gpmcadam
gpmcadam

Reputation: 6550

MSDN has a great article on comparing strings, but you may want to refer to the String documentation for specific help, most notably: String.Compare, String.CompareTo, String.IndexOf, and String.Substring.

Upvotes: 1

Related Questions