Kylin/Universal/StringUtility.h

71 lines
2.6 KiB
C
Raw Normal View History

2023-07-21 15:46:12 +08:00
#ifndef STRINGUTILITY_H
#define STRINGUTILITY_H
#include <string>
#include <vector>
namespace std {
template <class CharT, class Traits>
std::basic_string<CharT, Traits> to_string(const std::basic_string_view<CharT, Traits> &str) {
return std::basic_string<CharT, Traits>(str.begin(), str.end());
}
} // namespace std
namespace Amass {
namespace StringUtility {
template <typename CharT>
std::vector<std::basic_string<CharT>> split(const std::basic_string<CharT> &string,
const std::basic_string_view<CharT> &delimiter) {
std::vector<std::basic_string<CharT>> ret;
if (delimiter.empty() || string.empty()) return ret;
auto buf = string;
size_t pos = std::string::npos;
size_t delimiterLength = delimiter.length();
while (true) {
pos = buf.find(delimiter);
if (pos != std::basic_string<CharT>::npos) {
auto substr = buf.substr(0, pos);
if (!substr.empty()) ret.push_back(substr);
buf = buf.substr(pos + delimiterLength);
} else {
if (!buf.empty()) ret.push_back(buf);
break;
}
}
return ret;
}
inline std::vector<std::string> split(const std::string &string, const std::string_view &delimiter) {
return split<char>(string, delimiter);
}
std::string &replace(std::string &string, const std::string &before, const std::string &after);
template <typename CharT>
std::basic_string<CharT> trimmed(const std::basic_string<CharT> &string) {
static const CharT *whitespace = std::is_same_v<CharT, char> ? reinterpret_cast<const CharT *>("\t\n\v\f\r ")
: reinterpret_cast<const CharT *>(L"\t\n\v\f\r ");
auto begin = string.find_first_not_of(whitespace);
if (begin == std::basic_string<CharT>::npos) return std::basic_string<CharT>();
auto end = string.find_last_not_of(whitespace);
if (end == std::basic_string<CharT>::npos) return std::basic_string<CharT>();
return string.substr(begin, end - begin + 1);
}
bool equal(std::string_view lhs, std::string_view rhs, bool caseSensitivity = true);
size_t utf8Length(const std::string &text);
std::string_view utf8At(const std::string &text, size_t index);
size_t utf8CharacterByteSize(const char *character);
std::wstring stringToWString(const std::string &string);
2024-05-28 21:18:38 +08:00
std::string wstringToString(const std::wstring &string);
2024-06-13 10:08:09 +08:00
std::string UTF8ToGBK(const std::string &utf8Str);
2023-07-21 15:46:12 +08:00
} // namespace StringUtility
} // namespace Amass
#endif // STRINGUTILITY_H