使用此字符串重新格式化器使用什么代替 substr
What to use instead of substr for this string reformater?
所以我的教授告诉我,我必须重做我的代码,因为我在我的代码中使用了substr函数来完成它。此代码使用函数将用户输入的日期(如 2017 年 10 月 5 日(重新格式化为 2017-02-05。有没有人对如何在这个 c++ 程序中使用 substr 有任何想法?非常感谢以下代码的任何帮助:
#include <iostream>
#include <vector>
#include <sstream>
#include <cstdio>
using namespace std;
string reformatDate(string oldDate) {
string finalDate;
int d = 0;
int m;
int y = 0;
string month[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int i;
for (i = 0; i < oldDate.length(); i++) {
if(oldDate[i] >= '0' && oldDate[i] <= '9') {
d = d*10 + oldDate[i] - '0';
} else {
break;
}
}
i = i+3;
for(m = 1; m <=12; m++) {
if(month[m-1].compare(oldDate.substr(i,3)) == 0) {
break;
}
}
for(i=i+4; i<oldDate.length(); i++) {
if((oldDate[i] >= '0') && (oldDate[i] <= '9')) {
y = y*10+ oldDate[i] - '0';
} else {
break;
}
}
char str[20];
sprintf(str, "%d-%02d-%02d", y, m, d); // formats date into YYYY-MM-DD format
finalDate = finalDate + str;
return finalDate;
}
int main() {
string s;
cout << "Enter date: ";
getline(cin, s);
cout << "Reformated Date: " << reformatDate(s) << endl;
}
如您所见,我实际上只使用了一次substr,由于这一行而不得不重做整个事情会很痛苦。所以我需要的是一种解决方法,以使相同的代码在没有 substr 的情况下工作。谢谢!
对于不了解很多功能的人来说,这是一种简单的方法......当然可以做得更容易,但我认为你的教授想用这么简单的方法测试你......祝你好运!
i = i+1;
int k;
int count;
for(m = 1; m <=12; m++) {
for(k=0; k<3;k++) {
if(month[m-1][k] == oldDate[i+k]) {
count++;
}
}
if (count==3)
break;
else
count=0;
}
编写自己的方法,实现与string::substr
相同的功能。
这是我的看法,但我鼓励你也尝试写一个,这就是为什么你的教授告诉你重写代码=(
std::string mysubstr(std::string& str, size_t pos, size_t len)
{
std::string sub_str = "";
for(size_t i = 0; i < str.size(); ++i)
{
if(i == pos)
{
for(size_t j = 0; j < len; ++j)
sub_str += str[i++];
break;
}
}
return sub_str;
}
它可以在您的代码中使用,如下所示:
if(month[m-1].compare(mysubstr(oldDate, i, 3)) == 0)
或者像这样:
if(month[m-1] == mysubstr(oldDate, i, 3))
并为给定的输入生成相同的精确输出。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- c++库的公共头文件中应该包含什么
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- ifstream什么都没读
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- 使用此字符串重新格式化器使用什么代替 substr
- 字符串::substr() 在 C++ 中的运行时是什么
- std::string::substr成员函数的复杂性是什么?