
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
#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
Advertisements