如何将字符 * 字符串 = "2001-02-03"转换为整数格式?

How to translate char * string = "2001-02-03" to integer format?

本文关键字:转换 2001-02-03 整数 格式 字符 字符串      更新时间:2023-10-16

我有这些字符串:

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

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

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

的例子:Const char * date = "2001-02-03";-> int int_date = 20010203;Const char * id = "987654/3210";-> long long_id = 9876543210;

怎么办?

如果您有字符串,仅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
}

(我建议我的代码只是作为一个例子)