0

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"?

3
  • I mean that if my input is same with ****01** . For example: if(input=="20090101") { ... } In this compare, 01 is more important for me . How can I specify 01 char ? thanks Commented Mar 28, 2010 at 1:02
  • That looks suspiciously like a date. Are you trying to match a date representing any day in January of any year? Commented Mar 28, 2010 at 1:18
  • I have updated your question to make it more clear based on your comment. Commented Mar 28, 2010 at 1:32

5 Answers 5

11

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.
}
Sign up to request clarification or add additional context in comments.

Comments

5

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".

1 Comment

This will throw an exception if the input is less than 6 characters.
3

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

2 Comments

The $ probably shouldn't be there.
How about @"^\d{4}01\d\d$"?
1

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.