/
StringUtil.h
81 lines (62 loc) · 2.73 KB
/
StringUtil.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* Copyright (C) 2013 Rainmeter Project Developers
*
* This Source Code Form is subject to the terms of the GNU General Public
* License; either version 2 of the License, or (at your option) any later
* version. If a copy of the GPL was not distributed with this file, You can
* obtain one at <https://www.gnu.org/licenses/gpl-2.0.html>. */
#ifndef RM_COMMON_STRINGUTIL_H_
#define RM_COMMON_STRINGUTIL_H_
#include <Windows.h>
#include <algorithm>
#include <cwctype>
#include <locale>
#include <string>
/*
** Helper class for case insensitive find function.
*/
template<typename CharT>
struct Is_Equal
{
Is_Equal(const std::locale& loc) : locale(loc) { }
bool operator()(CharT ch1, CharT ch2) { return std::toupper(ch1, locale) == std::toupper(ch2, locale); }
private:
const std::locale& locale;
};
namespace StringUtil {
std::string Narrow(const WCHAR* str, int strLen = -1, int cp = CP_ACP);
inline std::string Narrow(const std::wstring& str, int cp = CP_ACP) { return Narrow(str.c_str(), (int)str.length(), cp); }
inline std::string NarrowUTF8(const WCHAR* str, int strLen = -1) { return Narrow(str, strLen, CP_UTF8); }
inline std::string NarrowUTF8(const std::wstring& str) { return Narrow(str.c_str(), (int)str.length(), CP_UTF8); }
std::wstring Widen(const char* str, int strLen = -1, int cp = CP_ACP);
inline std::wstring Widen(const std::string& str, int cp = CP_ACP) { return Widen(str.c_str(), (int)str.length(), cp); }
inline std::wstring WidenUTF8(const char* str, int strLen = -1) { return Widen(str, strLen, CP_UTF8); }
inline std::wstring WidenUTF8(const std::string& str) { return Widen(str.c_str(), (int)str.length(), CP_UTF8); }
void LTrim(std::wstring& str);
void RTrim(std::wstring& str);
void Trim(std::wstring& str);
size_t StripLeadingAndTrailingQuotes(std::wstring& str, bool single = false);
void ToLowerCase(std::wstring& str);
void ToUpperCase(std::wstring& str);
void ToProperCase(std::wstring& str);
void ToSentenceCase(std::wstring& str);
void EscapeRegExp(std::wstring& str);
void EncodeUrl(std::wstring& str, bool doReserved = true);
bool CaseInsensitiveCompareN(std::wstring& str1, const std::wstring& str2);
/*
** Case insensitive find function for std::string and std::wstring.
**
** Modified from http://stackoverflow.com/questions/3152241/case-insensitive-stdstring-find#3152296
*/
template<typename T>
std::size_t CaseInsensitiveFind(const T& str1, const T& str2, const std::locale& loc = std::locale())
{
T::const_iterator iter = std::search(str1.begin(), str1.end(),
str2.begin(), str2.end(), Is_Equal<T::value_type>(loc));
if (iter != str1.end())
{
return (iter - str1.begin());
}
return -1; // not found
}
} // namespace StringUtil
#endif