在 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+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.