0

如何转换

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

对于这样的事情

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

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

这样我就可以通过使用将其转换为无符号的 __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 = %I64u\n", u );
}
4

6 回答 6

3
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,否则最后得到的整数小于预期(因此可能会混淆公元 2 年的日期/时间)。

于 2012-06-26T10:05:15.970 回答
2

如果您的编译器支持 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;
}
于 2012-06-26T10:11:12.543 回答
0

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

于 2012-06-26T10:02:47.287 回答
0
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]);
    }
}
于 2012-06-26T10:28:01.883 回答
0

干得好:

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));
于 2012-06-26T10:06:18.597 回答
0

我不会使用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多次使用可能会涉及更多的内存洗牌。

于 2012-06-26T10:09:04.977 回答