บทนำ
ในบทช่วยสอนนี้ เราจะหา จำนวนปีที่ไม่ซ้ำกัน (distinct years) ในสตริงที่มีวันที่อยู่ในรูปแบบ DD/MM/YYYY
ตัวอย่าง
Input: "Sample example with dates 01/11/2020, 02/12/2020, and 03/10/2019."
Output: 2 (ปี 2020 และ 2019)
ขั้นตอนการแก้ปัญหา
- กำหนดข้อความที่มีวันที่
- ใช้ Regular Expression (regex) ดึงวันที่ทั้งหมด
- ใช้ unordered_set เก็บปีเพื่อหาค่าที่ไม่ซ้ำ
- ดึง 4 ตัวอักษรสุดท้ายของแต่ละวันที่ (ปี)
- พิมพ์ขนาดของ set
ตัวอย่างโค้ด
#include <iostream>
#include <bits/stdc++.h>
#include <regex>
using namespace std;
int uniqueYearsCount(string text) {
// Regex สำหรับ DD/MM/YYYY
regex date_regex("[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}");
smatch matching_date;
unordered_set years;
// หาวันที่ทั้งหมด
while (regex_search(text, matching_date, date_regex)) {
string date = matching_date[0];
// ดึง 4 ตัวสุดท้าย (ปี)
years.insert(date.substr(date.size() - 4));
text = matching_date.suffix();
}
return years.size();
}
int main() {
string text = "Sample example with dates 01/11/2020, 02/12/2020, and 03/10/2019.";
cout << uniqueYearsCount(text) << endl;
return 0;
}
ผลลัพธ์
2
รูปแบบวันที่อื่นๆ
ถ้าวันที่อยู่ในรูปแบบอื่น (MM/DD/YYYY, YYYY-MM-DD, ฯลฯ) ให้ปรับ regex ตามนั้น เช่น:
- YYYY-MM-DD:
regex("[0-9]{4}-[0-9]{2}-[0-9]{2}")→ substr(0, 4) - MM/DD/YYYY:
regex("[0-9]{2}/[0-9]{2}/[0-9]{4}")→ substr(6, 4)
สรุป
ใช้ C++ regex และ unordered_set ดึงปีจากวันที่ในข้อความได้อย่างมีประสิทธิภาพ หากมีคำถาม สามารถถามได้ในส่วนความคิดเห็นครับ