Hani Goc
Hani Goc

Reputation: 2441

Find and convert a **date** in a string to its numeric form

I am extracting strings of dates from documents. Dates can have the following formats:

I want to check if a string contains the name of a month and then convert it to its numeric form. For example: 12 JAN 2014 ==> 12 1 2014, June 12 1999 ==> 6 12 1999 etc.

Upvotes: 0

Views: 76

Answers (1)

Hani Goc
Hani Goc

Reputation: 2441

I came out with the following solution: First I create a file with the dates and their numeric values

JANVIER 1
FEVRIER 2
MARS    3
AVRIL   4
MAI 5
JUIN    6
JUILLET 7
AOUT    8
SEPTEMBRE   9
OCTOBRE 10
NOVEMBRE    11
DECEMBRE    12

#include <boost/algorithm/string/replace.hpp>
#include <vector>
#include <iostream>

using namespace std;
vector<pair<string,int>> getDates();
bool dateExists(string,strin);

int main()
{
   //replace JANVIER
    string date = "JANVIER-12-1999";
    vector<pair<string,int>> d = getDates("dates.txt");
    for(size_t i = 0; i < d.size();i++)
    {
        string searchDate = d[i].first;

        if(dateExists(date,searchDate ))
        {
            string num = std::to_string(d[i].second);
            boost::replace_all(date, searchDate ,num );
        }
    }

    cout << date << endl;
    return 0;
}

vector<pair<string,int>> getDates(string path)
{
    vector<pair<string,int>> vec;


    boost::iostreams::stream<boost::iostreams::file_source> file(path.c_str());
    string line;

    while (std::getline(file, line))
    {
        std::vector<string> splitLine;
        boost::split(splitLine,line,boost::is_any_of("\t"));
        vec.push_back(make_pair(splitLine[0],atoi(splitLine[1].c_str())));
    }
    return vec;
}

bool dateExists(string str,string str2)
{
    if (str.find(str2) != string::npos)
        return true;
    else
        return false;

}//end function

Upvotes: 1

Related Questions