将日期和时间字符串转换为 C++ 中的整数
convertint date and time string to just integers in C++
如何转换
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]);
}
}
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- 如何在C++中将整数转换为其数字数组