简体   繁体   中英

Using C# to check if string contains a string in string array and how to connect it

basically i want the user to enter the month as a string, here is my code...

static void getAbbreviatedMonth() //dd/mmm/yyyy
        {

        do
        {
            Console.Write("PLease enter the year (not earlier than 1812) as 4 digits  >> ");

        } while (!int.TryParse(Console.ReadLine(), out y) || y < 1812);


        do
        {

            Console.Write("Please enter the month as a three letter `character ( e.g 'Jul'>> ");`

and this is my separate coding below and how would i code the coding on the top bit so that it checks and matches the string from below.

static bool isCorrectMonth(string monthToCheck)
        {
            string stringToCheck = monthToCheck;
            string[] stringArray = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
            foreach (string x in stringArray)
            {
                if (x.Contains(stringToCheck))
                {
                    // Process..
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

Per your example code I think it should be something like this however you should at least make it case insensitive by validating against all lower case :

do
{
  Console.Write("PLease enter the year (not earlier than 1812) as 4 digits  >> ");

} while (!int.TryParse(Console.ReadLine(), out y) || y < 1812);


do
{
  Console.Write("Please enter the month as a three letter character ( e.g 'Jul'>> ");
}   while (!isCorrectMonth(Console.ReadLine()) );       





static bool isCorrectMonth(string monthToCheck)
{
  string stringToCheck = monthToCheck.ToLower();
  string[] stringArray = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" };
  foreach (string x in stringArray)
  {
    if (x.Contains(stringToCheck))
    {
        // Process..
        return true;
    }
    else
    {
        return false;
    }
  }
  return false;
}           

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM