使用此字符串重新格式化器使用什么代替 substr

What to use instead of substr for this string reformater?

本文关键字:什么 substr 字符串 格式化      更新时间:2023-10-16

所以我的教授告诉我,我必须重做我的代码,因为我在我的代码中使用了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))

并为给定的输入生成相同的精确输出。