将月份名称转换为数字

Convert Month Name into Number C++

本文关键字:转换 数字      更新时间:2023-10-16

我已经很长时间没有接触过c++了,我相信这可以在一行代码中完成。

我有一个字符串day,我想将其转换为0-11之间的值。我通常会这样做

months = array('Jan', 'Feb', 'Mar', 'Apr' ...);
print months[day];

但是我不知道如何在c++中做到这一点

一个简单的方法是这样的:

vector<string> months = { "jan", "feb", "mar", "apr", "may", ... };
int month_number = 2;
cout << months[ month_number - 1 ] // it is month_number-1 because the array subscription is 0 based index.

一个更好,但更复杂和先进的方法是使用std::map,如下所示:

int get_month_index( string name )
{
    map<string, int> months
    {
        { "jan", 1 },
        { "feb", 2 },
        { "mar", 3 },
        { "apr", 4 },
        { "may", 5 },
        { "jun", 6 },
        { "jul", 7 },
        { "aug", 8 },
        { "sep", 9 },
        { "oct", 10 },
        { "nov", 11 },
        { "dec", 12 }
    };
    const auto iter = months.find( name );
    if( iter != months.cend() )
        return iter->second;
    return -1;
}

您可以使用std::map来编写这样的函数:

int GetMonthIndex(const std::string & monthName)
{
    static const std::map<std::string, int> months
    {
        { "Jan", 0 },
        { "Feb", 1 },
        { "Mar", 2 },
        { "Apr", 3 },
        { "May", 4 },
        { "Jun", 5 },
        { "Jul", 6 },
        { "Aug", 7 },
        { "Sep", 8 },
        { "Oct", 9 },
        { "Nov", 10 },
        { "Dec", 11 }
    };
    const auto iter(months.find(monthName));
    return (iter != std::cend(months)) ? iter->second : -1;
}

您可以使用一个简单的开关,或者std::map,这样比较省事