Search code examples
c++stringc++11tokenizesubstr

What to use instead of substr for this string reformater?


So my professor told me that I had to redo my code because I used substr function in my code in order to complete it. This code uses a function to reformat a user inputed date like 5th Oct 2017 into 2017-02-05. Does anyone have any ideas on how to get around using substr for this c++ program? Any help is greatly appreciated with the following code:

#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;
}

As you can see I only really use substr once and it would be a pain to have to redo this whole thing because of this one line. So what I need is a workaround in order to make this same code work without substr. Thanks!


Solution

  • This is a simple way for someone who does not know many functions... Of course can be done easier but I think your professor wants to test you in such simple methods... Good luck!

    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;
    
    }