在 C++ 中从字符串查找总共的年数


在本教程中,我们将讨论一个从字符串查找不同年份总数的程序。

为此,我们将提供一个包含 'DD-MM-YYYY' 格式日期的字符串。我们的任务是查找给定字符串中提到的不同年份的数量。

实例

 在线演示

#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;
}

输出

3

更新于: 2020 年 8 月 19 日

2K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始
广告