G
G
German2018-09-22 11:10:03
C++ / C#
German, 2018-09-22 11:10:03

How to compare string strings with dates of birth?

I have an array of strings:

string array_data[3] = {"13.11.1999", "09.10.1997", "22.05.1995"};

It is required to find the smallest date, in this case it is 05/22/1995 , it is clear that the usual string comparison will not help here, how to implement it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel, 2018-10-03
Yazovskikh @unepic

A suboptimal, but working solution that was already suggested to you, based on converting to the YYYYMMDD format:

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main(void)
{
  std::vector<std::string> array_data{ "13.11.1999", "09.10.1997", "22.05.1995" };
  auto as_yyyymmdd = [](const std::string& src){
    return src.substr(6,4) + src.substr(3,2) + src.substr(0,2); 
  };
  auto min_date_it = std::min_element(array_data.begin(), array_data.end(),
    [as_yyyymmdd](const std::string& a, const std::string& b){ 
      return as_yyyymmdd(a) < as_yyyymmdd(b);
    });
  std::string min_date = *min_date_it;
  std::cout << min_date << std::endl;
  return 0;
}

G
GavriKos, 2018-09-22
@GavriKos

There are many options:
- we parse separately in each line the day, month, year, and in ints, we compare.
- permutations bring to the form YYMMDD, convert to int, compare
- use which thread the class for working with dates (depends on the connected / valid libraries), which can parse from a string and compare

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question