将月份名称转换为数字
Convert Month Name into Number C++
我已经很长时间没有接触过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,这样比较省事
相关文章:
- 将数字转换为字母(例如:123 转换为一二三)
- 将数字转换为单词
- 使用if-else将数字转换为单词
- 将数字转换为填充字符串
- 函数在许多数字上转换为基数 1 时减去 2?
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何将 UTF-8 文本从文件转换为某个可以迭代的容器,并检查每个符号是否为C++字母数字?
- 将 C 函数转换为 C++ 以检查数字是否有效
- 编译时间文本到数字转换 (atoi)
- 以C++格式将字符串转换为数字
- 在 c++ 中将数字转换为矢量数组的函数
- 奇怪的数字转换C++
- 我想使用 std::stoi 函数在 cpp 中将字符串转换为整数,因为我想在字符串中找到不同数字的总和(在下级酶中)
- 用C++将浮点数字转换为本地化字符串
- 我需要静态转换我的数字模板值吗
- 如何将boost::asio::ip::address_v6 ip转换为2个uint64_t数字,并从2个uint 64
- Rcpp - 用二进制函数转换数字向量?
- 我如何使用堆栈转换数字从基数10到基数2在c++
- 如何在c++中从字节数组中的整数转换数字
- c++程序转换数字的位数