xref: /MusicPlayer2/MusicPlayer2/ChinesePingyinRes.cpp (revision f3728c8579270583f00105e28c21564840605bd9)
1 #include "stdafx.h"
2 #include "ChinesePingyinRes.h"
3 #include "Common.h"
4 #include "resource.h"
5 
CChinesePingyinRes()6 CChinesePingyinRes::CChinesePingyinRes()
7 {
8 }
9 
~CChinesePingyinRes()10 CChinesePingyinRes::~CChinesePingyinRes()
11 {
12 }
13 
Init()14 void CChinesePingyinRes::Init()
15 {
16     //载入资源
17     std::wstring pingyin_res = CCommon::GetTextResource(IDR_CHINESE_PINGYIN, CodeType::UTF8_NO_BOM);
18     std::wstringstream res_stream(pingyin_res);
19     while (true)
20     {
21         std::wstring str_line;
22         std::getline(res_stream, str_line);
23         if (str_line.empty())
24             break;
25 
26         if (str_line.back() == L'\r' || str_line.back() == L'\n')
27             str_line.pop_back();
28 
29         if (str_line.size() < 3)
30             continue;
31 
32         wchar_t charactor = str_line[0];
33         if (!IsChineseCharactor(charactor))
34             continue;
35 
36         std::wstring str_pingyin = str_line.substr(2);
37         if (!m_pingyin_map.contains(charactor))
38             m_pingyin_map[charactor] = str_pingyin;
39     }
40 }
41 
IsChineseCharactor(wchar_t ch)42 bool CChinesePingyinRes::IsChineseCharactor(wchar_t ch)
43 {
44     return ch >= 0x4E00 && ch <= 0x9FA5;
45 }
46 
IsStringMatchWithPingyin(const std::wstring & key_words,const std::wstring & compared_str)47 bool CChinesePingyinRes::IsStringMatchWithPingyin(const std::wstring& key_words, const std::wstring& compared_str)
48 {
49     //全部转换为小写
50     std::wstring key_words_tmp{ key_words };
51     std::wstring compared_str_tmp{ compared_str };
52     CCommon::StringTransform(key_words_tmp, false);
53     CCommon::StringTransform(compared_str_tmp, false);
54 
55     //直接匹配
56     if (compared_str_tmp.find(key_words_tmp) != std::wstring::npos)
57         return true;
58 
59     //构建被查找字符串的拼音全拼和首字母形式
60     std::wstring full_pinyin_str;
61     std::wstring initial_pinyin_str;
62 
63     for (const wchar_t& ch : compared_str_tmp)
64     {
65         if (IsChineseCharactor(ch) && m_pingyin_map.find(ch) != m_pingyin_map.end())
66         {
67             const std::wstring& pinyin{ m_pingyin_map[ch] };
68                 full_pinyin_str += pinyin;
69                 if (!pinyin.empty())
70                     initial_pinyin_str += pinyin[0];
71         }
72         else
73         {
74             full_pinyin_str.push_back(ch);
75             initial_pinyin_str.push_back(ch);
76         }
77     }
78 
79     //全拼匹配
80     if (full_pinyin_str.find(key_words_tmp) != std::wstring::npos)
81         return true;
82 
83 
84     //首字母匹配
85     if (initial_pinyin_str.find(key_words_tmp) != std::wstring::npos)
86         return true;
87 
88     return false;
89 }
90