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

In this tutorial, we will be discussing a program to find total number of distinct years from a string.

For this we will be provided with a string containing dates in format ‘DD-MM-YYYY’ format. Our task is to find the count of distinct years mentioned in the given string.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
//calculating the distinct years mentioned
int calculateDifferentYears(string str) {
   unordered_set<string> differentYears;
   string str2 = "";
   for (int i = 0; i < str.length(); i++) {
      if (isdigit(str[i])) {
      if (str[i] == '-') {
      if (str2.length() == 4) {
   return differentYears.size();
int main() {
   string sentence = "I was born on 22-12-1955."
   "My sister was born on 34-06-2003 and my mother on 23-03-1940.";
   cout << calculateDifferentYears(sentence);
   return 0;