簡體   English   中英

使用C#檢查字符串是否在字符串數組中包含字符串以及如何連接它

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

基本上我希望用戶以字符串形式輸入月份,這是我的代碼...

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'>> ");`

這是我下面的單獨編碼,我將如何在最高位上編碼該編碼,以便它從下面檢查並匹配字符串。

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;
        }

根據您的示例代碼,我認為應該是這樣,但是您至少應該通過對所有小寫字母進行驗證來使其不區分大小寫:

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;
}           

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM