将日期和时间字符串转换为 C++ 中的整数

convertint date and time string to just integers in C++

本文关键字:C++ 整数 转换 日期 时间 字符串      更新时间:2023-10-16

如何转换

std::string strdate = "2012-06-25 05:32:06.963";

对于这样的事情

std::string strintdate = "20120625053206963"//基本上我删除了 -、:、空格和 .

我想我应该使用 strtok 或字符串函数,但我做不到,任何人都可以在这里用 sampel 代码帮助我。

以便我使用 将其转换为无符号__int64

// crt_strtoui64.c
#include <stdio.h>
unsigned __int64 atoui64(const char *szUnsignedInt) {
   return _strtoui64(szUnsignedInt, NULL, 10);
}
int main() {
   unsigned __int64 u = atoui64("18446744073709551615");
   printf( "u = %I64un", u );
}
bool nondigit(char c) {
    return c < '0' || c > '9';
}
std::string strdate = "2012-06-25 05:32:06.963";
strdate.erase(
    std::remove_if(strdate.begin(), strdate.end(), nondigit),
    strdate.end()
);
std::istringstream ss(strdate);
unsigned __int64 result;
if (ss >> result) {
    // success
} else {
    // handle failure
}

顺便说一句,您作为 64 位 int 的表示可能有点脆弱。确保2012-06-25 05:32:06输入的日期/时间2012-06-25 05:32:06.000,否则您从末尾得到的整数小于预期(因此可能会混淆为 2AD 年的日期/时间)。

如果您的编译器支持 C++11 功能:

#include <iostream>
#include <algorithm>
#include <string>
int main()
{
    std::string s("2012-06-25 05:32:06.963");
    s.erase(std::remove_if(s.begin(),
                           s.end(),
                           [](const char a_c) { return !isdigit(a_c); }),
            s.end());
    std::cout << s << "n";
    return 0;
}

使用字符串替换将不需要的字符替换为没有字符的字符http://www.cplusplus.com/reference/string/string/replace/

你来了:

bool not_digit (int c) { return !std::isdigit(c); }
std::string date="2012-06-25 05:32:06.963";
// construct a new string
std::string intdate(date.begin(), std::remove_if(date.begin(), date.end(), not_digit));

我不会使用 strtok。下面是一个相当简单的方法,仅使用std::string成员函数:

std::string strdate = "2012-06-25 05:32:06.963";
size_t pos = strdate.find_first_not_of("1234567890");
while (pos != std::string::npos)
{
    size_t endpos = strdate.find_first_of("1234567890", pos);
    strdate.erase(pos, endpos - pos);
    pos = strdate.find_first_not_of("1234567890");
}

这不是一种超级有效的方法,但它会起作用。

也许更有效的方法可能会使用字符串流...

std::string strdate = "2012-06-25 05:32:06.963";
std::stringstream out;
for (auto i = strdate.begin(); i != strdate.end(); i++)
    if (std::isdigit(*i)) out << *i;
strdate = out.str();

我不对时间或空间复杂性做出任何承诺,但我怀疑多次使用string::erase可能会涉及更多的内存洗牌。

std::string strdate = "2012-06-25 05:32:06.963";
std::string result ="";
for(std::string::iterator itr = strdate.begin(); itr != strdate.end(); itr++)
{
    if(itr[0] >= '0' &&  itr[0] <= '9')
    {
        result.push_back(itr[0]);
    }
}