【问题标题】:How to translate char * string = "2001-02-03" to integer format?如何将 char * string = "2001-02-03" 转换为整数格式?
【发布时间】:2013-04-05 23:15:54
【问题描述】:

我有这些字符串:

const char * date = "2001-02-03";
const char * id = "987654/3210";

我需要非常快速地转换为整数或长整数(对于 id)。我需要翻译比较(因为数字 strcmp() 很慢)。我只有这个库:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

示例: 常量字符 * 日期 = "2001-02-03"; -> int int_date = 20010203; 常量字符 * id = "987654/3210"; -> long long_id = 9876543210;

怎么办?

【问题讨论】:

  • 提示:转换为 int + int 比较(可以忽略不计)不太可能比字符串比较快。如果比较多次,您只会从转换中受益。

标签: c++ integer type-conversion


【解决方案1】:

如果您有字符串,则只需strcmp 比将其转换(解析)为另一种格式然后进行比较要快。

但解析它的一种简单方法是:

const char * date = "2001-02-03";
int y, m, d;
int result = sscanf(date, "%d-%d-%d", &y, &m, &d);

if (result == 3)
{
    // use them
}

(我建议我的代码仅作为示例)

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 2011-08-13
    • 2012-07-29
    相关资源
    最近更新 更多