将一个字符串转换为另一个字符串时出现问题
Issues converting one string to another
我想将表单的日期strVal="1992-12-12"或"1992-9-9"转换为19921212&为此,我用C/C++编写了以下代码。但问题是它将1992-12-12转换为1992012012。有人能指导我如何修复这个bug吗?我可能还有"1992-9"表格的输入,我想将其转换为19920900。或"1992"至"19920000">
stringstream collectTimeBegin;
for (string::iterator it = strVal.begin(); it != strVal.end(); )
{
if (*it != '-')
{
cout<< "n -- *it=" << *it;
collectTimeBegin << *it;
it++;
}
else
{
stringstream si("");
stringstream sj("");
int i;
it++;
si << *(it + 1);
sj<< *(it + 2);
i = atoi((si.str()).c_str()), j = atoi((sj.str()).c_str());
cout << "n i=" << i << "t j=" << j << "n";
if ((i == 4) || (i == 5) || (i == 6) || (i == 7) || (i == 8) || (i == 9))
{
cout << "n 1. *it=" << *it;
collectTimeBegin << *it;
it++;
}
else if ((j == 0) || (j == 1) || (j == 2) || (j == 3) || (j == 4) ||
(j == 5) || (j == 6) || (j == 7) || (j == 8) || (j == 9))
{
string str = "0";
cout << "n 2. *it=" << *it;
collectTimeBegin << str;
collectTimeBegin << *it;
it++;
}
}
}
这里有一个使用标准C++的解决方案;它使用了与Christian相同的方法:根据破折号分割输入,用0填充缺失的数字:
#include <string>
#include <sstream>
#include <algorithm>
int main()
{
std::string date = "1992-9-12";
std::replace(date.begin(), date.end(), '-', ' '); // "1992 9 12"
std::istringstream iss(date);
int year = 0, month = 0, day = 0;
if (iss.good()) iss >> year; // 1992
if (iss.good()) iss >> month; // 9
if (iss.good()) iss >> day; // 12
std::ostringstream oss;
oss.fill('0');
oss.width(4); oss << year;
oss.width(2); oss << month;
oss.width(2); oss << day;
std::string convertedDate = oss.str(); // 19920912
}
如果你不介意使用外部库,我会用boost来完成。
string input = "1992-9-9";
vector<string> v;
boost::algorithm::split(v, input, boost::algorithm::is_any_of("-"));
string output;
BOOST_FOREACH(const string &s, v)
{
if (s.size() == 1)
{
output += "0"+s;
} else {
output += s;
}
}
if (output.size() == 4)
output += "0000"
if (output.size() == 6)
output += "00"
编辑:如果您的输入字符串只有6或4位数长,则忘记处理这种情况
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 使用另一个字符串从字符串中删除空格
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何在使用 getch 后在另一个字符串的末尾连接一个字符串
- 如何在另一个字符串的x位置插入一个字符串?
- 从 C 字符串构造 std::string 与从另一个 std::string 构造 std::string 不一致
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 在另一个字符串中插入文件扩展名之前的字符串
- 使用C++将一个字符串替换为另一个字符串
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将字符串中的单个单词替换为另一个单词
- 将文本流中一个字符串的所有匹配项替换为另一个字符串
- 无法将字符串用作另一个类的参数
- 另一个字符串文字,UDL 迷宫
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 如何使用循环从另一个字符串创建一个没有空格的新字符串