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

C++Server Side ProgrammingProgramming

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.

Example

 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])) {
         str2.push_back(str[i]);
      }
      if (str[i] == '-') {
         str2.clear();
      }
      if (str2.length() == 4) {
         differentYears.insert(str2);
         str2.clear();
      }
   }
   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;
}

Output

3
raja
Published on 19-Aug-2020 10:45:13
Advertisements