从C ++中的字符串中查找不同年份的总数
在本教程中,我们将讨论一个从字符串中查找不同年份总数的程序。
为此,我们将为您提供一个字符串,其中包含日期格式为“DD-MM-YYYY”的日期。我们的任务是查找给定字符串中提到的不同年份的计数。
示例
#include <bits/stdc++.h>
using namespace std;
//计算提到的不同年份
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