查找字符串中的 **date** 并将其转换为其数字形式

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

本文关键字:转换 数字 字形 字符串 date 查找      更新时间:2023-10-16

我正在从文档中提取日期字符串。日期可以具有以下格式:

  • 12 1月 2014
  • 六月12 1999
  • 19992月9
  • 2008-2-7

我想检查字符串是否包含月份的名称,然后将其转换为数字形式。例如:12 JAN 2014 ==> 12 1 2014, June 12 1999 ==> 6 12 1999 等。

我提出了以下解决方案:首先,我创建一个包含日期及其数值的文件

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