String contains only a given set of characters

前端 未结 7 1468
执笔经年
执笔经年 2021-02-18 13:22

I need to know if a given string is a valid DateTime format string because the string may represent other things. I tried DateTime.ParseExact(somedate.ToString(format), format)

7条回答
  •  迷失自我
    2021-02-18 13:54

    With .NET2, you need to roll your own check for this. For example, the following method uses a foreach to check:

    bool FormatValid(string format)
    {
        string allowableLetters = "yYmMdDsShH";
    
        foreach(char c in format)
        {
             // This is using String.Contains for .NET 2 compat.,
             //   hence the requirement for ToString()
             if (!allowableLetters.Contains(c.ToString()))
                  return false;
        }
    
        return true;
    }
    

    If you had the option of using .NET 3.5 and LINQ, you could use Enumerable.Contains to work with characters directly, and Enumerable.All. This would simplify the above to:

    bool valid = format.All(c => "yYmMdDsShH".Contains(c));
    

提交回复
热议问题