2013-04-13 23 views
0

我有這些字符串:如何將char * string =「2001-02-03」翻譯爲整數格式?

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

我需要非常快的轉換爲整數或可能長整型(用於ID)。我需要翻譯比較(數字strcmp()是慢)。我只有這個庫:

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

實施例: 常量字符*日期= 「2001年2月3日」; - > int int_date = 20010203; const char * id =「987654/3210」; - > long long_id =;

怎麼辦?

+2

提示:轉換爲int + INT比較(可忽略不計)是不太可能比字符串比較更快。如果多次**進行比較**,您只能從轉換中受益。 –

回答

0

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

(我建議我的代碼只是作爲一個樣本)