Find total number of distinct years from a string in C++ Program


In this tutorial, we are going to write a program that finds distinct years in the given string. Let's see some examples. We are assuming the date format is DD/MM/YYYY.

Input − Sample example with dates 01/11/2020, 02/12/2020, and 03/10/2019.

Output − 2

We have two distinct years in the given text 2020 and 2019.

We are going to use regex to extract all dates from the given string. If you are not familiar with regex in C++, go through this tutorial.

Let's jump into solving the problem.

  • Initialize the text.

  • Write the regex to extract dates from the text.

  • Initialize an empty unordered set.

  • Iterate over the dates and add year to the unordered set to find unique years.

  • Print the length of the set.

Example

Let's see the code.

 Live Demo

#include <iostream>
#include <bits/stdc++.h>
#include <regex>
using namespace std;
int uniqueYearsCount(string text) {
   // regex
   regex date_regex("[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}");
   smatch matching_date;
   // set to store unique dates
   unordered_set<string> dates;
   // finding all dates
   while (regex_search(text, matching_date, date_regex)) {
      string date = matching_date[0];
      dates.insert(date.substr(date.size() - 4));
      text = matching_date.suffix();
   }
   return dates.size();
}
int main() {
   string text = "Sample example with dates 01/11/2020, 02/12/2020, and 03/10/2019.";
   cout << uniqueYearsCount(text) << endl;
   return 0;
}

Output

If run the above code, then you will get the following result.

2

We can get dates in a different formats. If you get dates in different formats, then update the regex appropriately.

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 29-Dec-2020

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements