Programing

C #에서 비교하기 위해 월 이름 (문자열)을 정수로 구문 분석하는 방법은 무엇입니까?

lottogame 2020. 9. 6. 11:50
반응형

C #에서 비교하기 위해 월 이름 (문자열)을 정수로 구문 분석하는 방법은 무엇입니까?


배열에있는 몇 가지 달 이름을 비교할 수 있어야합니다.

다음과 같은 직접적인 방법이 있다면 좋을 것입니다.

Month.toInt("January") > Month.toInt("May")

내 Google 검색이 유일한 방법은 자신의 방법을 작성하는 것 같지만 이것은 이미 .Net에서 구현되었을 것이라고 생각할 정도로 일반적인 문제처럼 보입니다.


DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month

비록 당신의 목적을 위해, 당신은 아마도 Dictionary<string, int>그 달의 이름을 그 값에 매핑하는 것을 만드는 것이 더 나을 것입니다 .


다음과 같이 할 수 있습니다.

Convert.ToDate(month + " 01, 1900").Month

DateTime.ParseExact()여러 사람이 제안한 -method 를 사용하는 경우 응용 프로그램이 영어가 아닌 환경에서 실행될 때 수행 할 작업을 신중하게 고려해야합니다!

덴마크는 어떤이 ParseExact("Januar", ...)ParseExact("January", ...)작업을해야하고 어떤 실패 하는가?

그 차이 것 CultureInfo.CurrentCultureCultureInfo.InvariantCulture.


DateTime.Parse 메서드를 사용하여 DateTime 개체를 가져온 다음 해당 Month 속성을 확인할 수 있습니다. 다음과 같이하십시오.

int month = DateTime.Parse("1." + monthName + " 2008").Month;

트릭은 유효한 날짜를 작성하여 DateTime 객체를 만드는 것입니다.


달의 열거 형을 사용할 수 있습니다.

public enum Month
{
    January,
    February,
    // (...)
    December,
}    

public Month ToInt(Month Input)
{
    return (int)Enum.Parse(typeof(Month), Input, true));
}

하지만 enum.Parse () 구문에 대해 100 % 확신하지는 않습니다.


이를 위해 DateTime 인스턴스를 만들 필요가 없습니다. 다음과 같이 간단합니다.

public static class Month
{
    public static int ToInt(this string month)
    {
        return Array.IndexOf(
            CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
            month.ToLower(CultureInfo.CurrentCulture))
            + 1;
    }
}

나는 da-DK문화에서 실행 중이므로이 단위 테스트는 통과합니다.

[Theory]
[InlineData("Januar", 1)]
[InlineData("Februar", 2)]
[InlineData("Marts", 3)]
[InlineData("April", 4)]
[InlineData("Maj", 5)]
[InlineData("Juni", 6)]
[InlineData("Juli", 7)]
[InlineData("August", 8)]
[InlineData("September", 9)]
[InlineData("Oktober", 10)]
[InlineData("November", 11)]
[InlineData("December", 12)]
public void Test(string monthName, int expected)
{
    var actual = monthName.ToInt();
    Assert.Equal(expected, actual);
}

독자가 명시적인 CultureInfo를 전달할 수있는 오버로드를 만드는 연습으로 남겨 두겠습니다.


한 가지 간단한 해결책은 이름과 값이있는 사전을 만드는 것입니다. 그런 다음 Contains ()를 사용하여 올바른 값을 찾을 수 있습니다.

Dictionary<string, string> months = new Dictionary<string, string>()
{
                { "january", "01"},
                { "february", "02"},
                { "march", "03"},
                { "april", "04"},
                { "may", "05"},
                { "june", "06"},
                { "july", "07"},
                { "august", "08"},
                { "september", "09"},
                { "october", "10"},
                { "november", "11"},
                { "december", "12"},
};
foreach (var month in months)
{
    if (StringThatContainsMonth.ToLower().Contains(month.Key))
    {
        string thisMonth = month.Value;
    }
}

And answering this seven years after the question was asked, it is possible to do this comparison using built-in methods:

Month.toInt("January") > Month.toInt("May")

becomes

Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
                 t => t.Equals("January", StringComparison.CurrentCultureIgnoreCase)) >
Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
                 t => t.Equals("May", StringComparison.CurrentCultureIgnoreCase))

Which can be refactored into an extension method for simplicity. The following is a LINQPad example (hence the Dump() method calls):

void Main()
{
    ("January".GetMonthIndex() > "May".GetMonthIndex()).Dump();
    ("January".GetMonthIndex() == "january".GetMonthIndex()).Dump();
    ("January".GetMonthIndex() < "May".GetMonthIndex()).Dump();
}

public static class Extension {
    public static int GetMonthIndex(this string month) {
        return Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
                         t => t.Equals(month, StringComparison.CurrentCultureIgnoreCase));
    }
}

With output:

False
True
True

If you are using c# 3.0 (or above) you can use extenders


I translate it into C# code in Spanish version, regards:

public string ObtenerNumeroMes(string NombreMes){

       string NumeroMes;   

       switch(NombreMes) {

        case ("ENERO") :
            NumeroMes = "01";
            return NumeroMes;

        case ("FEBRERO") :
            NumeroMes = "02";
            return NumeroMes;

        case ("MARZO") :
            NumeroMes = "03";
            return NumeroMes;

        case ("ABRIL") :
            NumeroMes = "04";
            return NumeroMes;

        case ("MAYO") :
            NumeroMes = "05";
            return NumeroMes;

        case ("JUNIO") :
            NumeroMes = "06";
            return NumeroMes;

        case ("JULIO") :
            NumeroMes = "07";
            return NumeroMes;

        case ("AGOSTO") :
            NumeroMes = "08";
            return NumeroMes;

        case ("SEPTIEMBRE") :
            NumeroMes = "09";
            return NumeroMes;

        case ("OCTUBRE") :
            NumeroMes = "10";
            return NumeroMes;

        case ("NOVIEMBRE") :
            NumeroMes = "11";
            return NumeroMes;

        case ("DICIEMBRE") :
            NumeroMes = "12";
            return NumeroMes;

            default:
            Console.WriteLine("Error");
            return "ERROR";

        }

   }

Public Function returnMonthNumber(ByVal monthName As String) As Integer
    Select Case monthName.ToLower
        Case Is = "january"
            Return 1
        Case Is = "february"
            Return 2
        Case Is = "march"
            Return 3
        Case Is = "april"
            Return 4
        Case Is = "may"
            Return 5
        Case Is = "june"
            Return 6
        Case Is = "july"
            Return 7
        Case Is = "august"
            Return 8
        Case Is = "september"
            Return 9
        Case Is = "october"
            Return 10
        Case Is = "november"
            Return 11
        Case Is = "december"
            Return 12
        Case Else
            Return 0
    End Select
End Function

caution code is in Beta version.


What I did was to use SimpleDateFormat to create a format string, and parse the text to a date, and then retrieve the month from that. The code is below:

int year = 2012 \\or any other year
String monthName = "January" \\or any other month
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
int monthNumber = format.parse("01-" + monthName + "-" + year).getMonth();

참고URL : https://stackoverflow.com/questions/258793/how-to-parse-a-month-name-string-to-an-integer-for-comparison-in-c

반응형