c++ - 从字符串中标记/提取信息的最佳方法

标签 c++ string datetime tokenize

我正在尝试将接收到的日期时间转换为特定格式以插入到 MySQL 数据库中。该程序是用 C++ 编写的,以下解决方案有效,但我觉得它效率低得可怕。

输入是:Mon Nov 08 17:41:23 +0000 2010
所需的输出格式为:YYYY-MM-DD HH:MM:SS
所以对于这个例子,输出将是:2010-11-08 17:41:23

我已经包含了代码的相关部分。

    //class variable
    std::map<std::string, std::string> monthMap;

void processor::initializeMonthMap(){
    monthMap["Jan"] = "01";
    monthMap["Feb"] = "02";
    monthMap["Mar"] = "03";
    monthMap["Apr"] = "04";
    monthMap["May"] = "05";
    monthMap["Jun"] = "06";
    monthMap["June"] = "06";
    monthMap["Jul"] = "07";
    monthMap["July"] = "07";
    monthMap["Aug"] = "08";
    monthMap["Sept"] = "09";
    monthMap["Sep"] = "09";
    monthMap["Oct"] = "10";
    monthMap["Nov"] = "11";
    monthMap["Dec"] = "12";
}

inline std::string processor::convertDate(std::string input) {
    //Format: Mon Nov 08 17:41:23 +0000 2010
    //To get to YYYY-MM-DD HH:MM:SS

    std::stringstream  newString(input);
    std::string temp1;
    std::string temp2;

    // Read Day in txt, discard
    newString >> temp1;

    //Read month, convert to number
    newString >> temp1;
    temp2 = "-" + monthMap[temp1] + "-";

    //Read Day in number
    newString >> temp1;
    temp2.append(temp1 + " ");

    //Read TimeStamp
    newString >> temp1;
    temp2.append(temp1);

    //Discard UTM adjustment
    newString >> temp1;

    //Read year
    newString >> temp1;

    //Add year to beginning of input
    temp1.append(temp2);

    return temp1;
}

最佳答案

您正在解析字符串,幸运的是您可以通过简单的追加来构建输出。我认为这并没有变得更有效率。

但是,您似乎可以使用 seekg 将光标定位到星期几和 UTM 调整之后。

http://www.cplusplus.com/reference/iostream/istream/seekg/

关于c++ - 从字符串中标记/提取信息的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4752605/

相关文章:

c++ - 在多继承场景下使用虚基类时,是不是所有的派生类都需要引用虚基类?

c++ - 使用任何缓冲区来存储任何数据,并放置 new 和 memcpy

c++ - 如何以通用方式解析 XML 文件

swift - 使用 Swift 从 NSTextfield 到 (const unsigned char *)

string - Matlab:将数字数组转换为字符串数组

连接字符串中的 Javascript 构造

python - TypeError : strptime() argument 1 must be str, 不是 datetime.date Python

c++ - CString 数组 -> 内存泄漏?

r - 查找 R 中两个时间戳之间的重叠以分配类次

python - Django - 格式化计算间隔