String compare in C#
I have a string like 20090101
and I want to compare it with 开发者_JAVA技巧????01??
.
if (input == "----01--") { .... }
How can I compare the 5th and 6th characters with "01"?
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.
}
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"
.
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) ...) ...
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
.
As Bauer said you can use String functions, also you can convert string to Char Array and work with it char by char
精彩评论