#include "pch.h" #include "CLewaimaiString.h" #include #include #include #include #include #include using namespace boost::archive::iterators; unsigned char ToHex(unsigned char x) { return x > 9 ? x + 55 : x + 48; } unsigned char FromHex(unsigned char x) { unsigned char y; if(x >= 'A' && x <= 'Z') { y = x - 'A' + 10; } else if(x >= 'a' && x <= 'z') { y = x - 'a' + 10; } else if(x >= '0' && x <= '9') { y = x - '0'; } else { assert(0); } return y; } CLewaimaiString::CLewaimaiString() { } CLewaimaiString::~CLewaimaiString() { } bool CLewaimaiString::base64_encode(const std::string& input, std::string* output) { typedef base64_from_binary> Base64EncodeIterator; std::stringstream result; try { copy(Base64EncodeIterator(input.begin()), Base64EncodeIterator(input.end()), std::ostream_iterator(result)); } catch(...) { return false; } size_t equal_count = (3 - input.length() % 3) % 3; for(size_t i = 0; i < equal_count; i++) { result.put('='); } *output = result.str(); return output->empty() == false; } bool CLewaimaiString::base64_decode(const std::string& input, std::string* output) { typedef transform_width, 8, 6> Base64DecodeIterator; std::stringstream result; try { copy(Base64DecodeIterator(input.begin()), Base64DecodeIterator(input.end()), std::ostream_iterator(result)); } catch(...) { return false; } *output = result.str(); return output->empty() == false; } void CLewaimaiString::trim(std::string& s) { if(!s.empty()) { s.erase(0, s.find_first_not_of(" ")); s.erase(s.find_last_not_of(" ") + 1); } } std::string CLewaimaiString::UrlEncode(const std::string& str) { std::string strTemp = ""; size_t length = str.length(); for(size_t i = 0; i < length; i++) { if(isalnum((unsigned char)str[i]) || (str[i] == '-') || (str[i] == '_') || (str[i] == '.') || (str[i] == '~')) { strTemp += str[i]; } else if(str[i] == ' ') { strTemp += "+"; } else { strTemp += '%'; strTemp += ToHex((unsigned char)str[i] >> 4); strTemp += ToHex((unsigned char)str[i] % 16); } } return strTemp; } std::string CLewaimaiString::UrlDecode(const std::string& str) { std::string strTemp = ""; size_t length = str.length(); for(size_t i = 0; i < length; i++) { if(str[i] == '+') { strTemp += ' '; } else if(str[i] == '%') { assert(i + 2 < length); unsigned char high = FromHex((unsigned char)str[++i]); unsigned char low = FromHex((unsigned char)str[++i]); strTemp += high * 16 + low; } else { strTemp += str[i]; } } return strTemp; } std::string CLewaimaiString::UnicodeToUTF8(const std::wstring& wstr) { if (wstr.empty()) return {}; int n = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr); if (n <= 0) return {}; // UTF-8 非法序列也会返回 0 std::string result(n, 0); // 先留 null 位 WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &result[0], n, nullptr, nullptr); result.resize(n - 1); // 去掉结尾 '\0' return result; } std::wstring CLewaimaiString::UTF8ToUnicode(const std::string& str) { if (str.empty()) return {}; int n = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0); if (n <= 0) return {}; std::wstring result(n, 0); MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &result[0], n); result.resize(n - 1); return result; } std::string CLewaimaiString::UnicodeToGBK(const std::wstring& wstr) { if (wstr.empty()) return {}; int n = WideCharToMultiByte(936, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr); if (n <= 0) return {}; // 转换失败保护 std::string result(n, 0); // 先留 null 的位置 WideCharToMultiByte(936, 0, wstr.c_str(), -1, &result[0], n, nullptr, nullptr); result.resize(n - 1); // 去掉结尾 '\0',size 准确 return result; } std::wstring CLewaimaiString::GBKToUnicode(const std::string& src) { if (src.empty()) return {}; int n = MultiByteToWideChar(936, 0, src.c_str(), -1, nullptr, 0); if (n <= 0) return {}; std::wstring result(n, 0); MultiByteToWideChar(936, 0, src.c_str(), -1, &result[0], n); result.resize(n - 1); return result; } std::string CLewaimaiString::UTF8ToGBK(const std::string& str) { std::wstring wsUnicode = CLewaimaiString::UTF8ToUnicode(str); std::string sGBK = CLewaimaiString::UnicodeToGBK(wsUnicode); return sGBK; } std::string CLewaimaiString::GBKToUTF8(const std::string& str) { std::wstring wsUnicode = CLewaimaiString::GBKToUnicode(str); std::string sUtf8 = CLewaimaiString::UnicodeToUTF8(wsUnicode); return sUtf8; } std::string CLewaimaiString::DoubleToString(const double value, unsigned int precisionAfterPoint) { char str[256]; std::string pre = "%." + std::to_string(precisionAfterPoint) + "f"; sprintf_s(str, pre.c_str(), value); std::string result = str; return result; } bool CLewaimaiString::isIPAddressValid(const char* pszIPAddr) { if(!pszIPAddr) { return false; //若pszIPAddr为空 } char IP1[100], cIP[4]; int len = strlen(pszIPAddr); int i = 0, j = len - 1; int k, m = 0, n = 0, num = 0; //去除首尾空格(取出从i-1到j+1之间的字符): while(pszIPAddr[i++] == ' '); while(pszIPAddr[j--] == ' '); for(k = i - 1; k <= j + 1; k++) { IP1[m++] = *(pszIPAddr + k); } IP1[m] = '\0'; char* p = IP1; while(*p != '\0') { if(*p == ' ' || *p < '0' || *p > '9') { return false; } cIP[n++] = *p; //保存每个子段的第一个字符,用于之后判断该子段是否为0开头 int sum = 0; //sum为每一子段的数值,应在0到255之间 while(*p != '.' && *p != '\0') { if(*p == ' ' || *p < '0' || *p > '9') { return false; } sum = sum * 10 + *p - 48; //每一子段字符串转化为整数 p++; } if(*p == '.') { if((*(p - 1) >= '0' && *(p - 1) <= '9') && (*(p + 1) >= '0' && *(p + 1) <= '9')) //判断"."前后是否有数字,若无,则为无效IP,如“1.1.127.” { num++; //记录“.”出现的次数,不能大于3 } else { return false; } }; if((sum > 255) || (sum > 0 && cIP[0] == '0') || num > 3) { return false; //若子段的值>255或为0开头的非0子段或“.”的数目>3,则为无效IP } if(*p != '\0') { p++; } n = 0; } if(num != 3) { return false; } return true; } /* * 把字符串in 以 delim为分隔符,转化为vector,比如 1,2,3,4,5,用逗号分隔,转化为5个元素的vector */ std::vector CLewaimaiString::Split(const std::string& in, const std::string& delim) { std::vector ret; if (in == "") { //空字符串,直接返回空vector return ret; } try { std::regex re{ delim }; return std::vector { std::sregex_token_iterator(in.begin(), in.end(), re, -1), std::sregex_token_iterator() }; } catch(const std::exception& e) { std::cout << "error:" << e.what() << std::endl; } return ret; } std::string CLewaimaiString::Merge(const std::vector& in, const std::string& delim) { std::string ret = ""; for (size_t i = 0; i < in.size(); i++) { ret += in[i]; if (i < in.size() - 1) { ret += delim; } } return ret; } /* *nNum是表示替换几个,默认为1表示替换第1个 **/ int CLewaimaiString::Replace(std::wstring& strContent, std::wstring strReplace, std::wstring strDest, int nNum) { int nCount = 0; while(true) { size_t pos = strContent.find(strReplace); if(pos != std::wstring::npos) { WCHAR pBuf[1] = { L'\0' }; strContent.replace(pos, strReplace.length(), pBuf, 0); strContent.insert(pos, strDest); nCount++; if(nCount == nNum) { break; } } else { break; } } return 0; } //整个替换所有的字符串,把strBig钟的strsrc全部替换成strdst void CLewaimaiString::string_replace(std::string &strBig, const std::string &strsrc, const std::string &strdst) { std::string::size_type pos = 0; std::string::size_type srclen = strsrc.size(); std::string::size_type dstlen = strdst.size(); while ((pos = strBig.find(strsrc, pos)) != std::string::npos) { strBig.replace(pos, srclen, strdst); pos += dstlen; } } //从文件路径或者url中获取文件名 std::string CLewaimaiString::GetFilenameFromUrl(std::string url) { if (url.empty()) return std::string(); // 截取掉查询字符串和片段标识 size_t end = url.find_first_of("?#"); if (end == std::string::npos) end = url.size(); // 找到最后一个 '/',取其后面的部分作为文件名 size_t pos = (end == 0) ? std::string::npos : url.find_last_of('/', end - 1); size_t start = (pos == std::string::npos) ? 0 : pos + 1; if (start >= end) return std::string(); std::string name = url.substr(start, end - start); // 对 %XX 编码进行解码(返回 UTF-8 字节序列) auto hexVal = [](char c) -> int { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); return -1; }; std::string decoded; decoded.reserve(name.size()); for (size_t i = 0; i < name.size(); ++i) { char c = name[i]; if (c == '%' && i + 2 < name.size()) { int hi = hexVal(name[i + 1]); int lo = hexVal(name[i + 2]); if (hi != -1 && lo != -1) { char ch = static_cast((hi << 4) | lo); decoded.push_back(ch); i += 2; continue; } } decoded.push_back(c); } return decoded; } //得到文件路径的目录 std::string CLewaimaiString::GetPathDir(std::string filePath) { std::string dirPath = filePath; size_t p = filePath.find_last_of(L'\\'); if (p != -1) { dirPath.erase(p); } return dirPath; } std::string CLewaimaiString::BuZifuLeft(std::string old, int num, const char zifu) { return std::string(num, zifu) + old; } std::string CLewaimaiString::GetQuweima(std::wstring input) { //先转换成GB2312,区位码都是相对于GB2312的 std::string gb_hanzi = CLewaimaiString::UnicodeToGBK(input); std::string result = ""; for (size_t i = 0; i < gb_hanzi.length() - 1; ) { byte* cur = (byte*)(gb_hanzi.c_str() + i); if (*cur >= 0 && *cur <= 127) { //正常的asicc码,字符串或者数字 int front = (short)(*cur - '\0'); front -= 32; if (front < 10) { result += "030" + std::to_string(front); } else { result += "03" + std::to_string(front); } i++; } else { int front = (short)(cur[0] - '\0');//将字节数组的第一位转换成short类型,这里(short)code[0]也是可以的 int back = (short)(cur[1] - '\0');//将字节数组的第二位转换成short类型 std::string s_front = std::to_string(front - 160); if (front - 160 < 10) { //前面补0 s_front = "0" + s_front; } std::string s_back = std::to_string(back - 160); if (back - 160 < 10) { //前面补0 s_back = "0" + s_back; } result += s_front + s_back; i++; i++; } } return result; } std::string CLewaimaiString::GetBarcodeCheckCode(const std::string& barcode) { if (barcode.length() != 12 || !CLewaimaiString::is_only_number(barcode)) { return ""; } int sum = 0; for (size_t i = 0; i < barcode.length(); ++i) { int digit = barcode[i] - '0'; sum += digit * (i % 2 == 0 ? 1 : 3); } return std::to_string((10 - sum % 10) % 10); } std::string CLewaimaiString::SqlZhuanyi(std::string old) { CLewaimaiString::string_replace(old, "'", "''"); return old; } std::wstring CLewaimaiString::ShuziInputFormat(std::wstring old, std::wstring input) { if (old == L"0") { if (input == L".") { return old + input; } else if(input == L"0") { return L"0"; } else { return input; } } int pos = old.find(L"."); if (pos != old.npos) { //已经有一个.了 if (input == L".") { return old; } if (old.length() - pos > 2) { //小数点后已经有2个数字了 return old; } return old + input; } else { //还没有小数点 return old + input; } } bool CLewaimaiString::is_only_number(std::string str) { for (size_t i = 0; i < str.size(); i++) { if ((str.at(i) > '9') || (str.at(i) < '0')) { return false; } } return true; } std::string CLewaimaiString::GenerateRandomStr(size_t len, bool useTimeSeed) { // 1. 定义字符集:大小写字母 + 数字(可自行增删) const std::string charset = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; if (len == 0 || charset.empty()) { return ""; } // 2. 生成时间种子(关键:精确到微秒,不同时间种子一定不同) std::random_device rd; // 硬件随机数(辅助增强随机性) uint64_t timeSeed = 0; if (useTimeSeed) { // 获取当前系统时间戳(从1970年1月1日到现在的微秒数) auto now = std::chrono::system_clock::now().time_since_epoch(); timeSeed = std::chrono::duration_cast(now).count(); } // 3. 初始化随机数生成器(混合硬件随机数 + 时间种子) std::mt19937_64 rng; if (useTimeSeed) { rng.seed(rd() ^ timeSeed); // 时间+硬件双重种子 } else { rng.seed(rd()); } // 4. 均匀分布:随机取字符集里的字符 std::uniform_int_distribution<> dist(0, (int)charset.size() - 1); // 5. 生成字符串 std::string result; result.reserve(len); // 预分配内存,提升效率 for (size_t i = 0; i < len; ++i) { result += charset[dist(rng)]; } return result; } std::string CLewaimaiString::TrimDecimalZero(const std::string& str) { std::string result = str; size_t dotPos = result.find('.'); if (dotPos == std::string::npos) { return result; } size_t lastNotZero = result.find_last_not_of('0'); if (lastNotZero == std::string::npos) { return result; } result.erase(lastNotZero + 1); if (!result.empty() && result[result.length() - 1] == '.') { result.erase(result.length() - 1); } return result; } std::wstring CLewaimaiString::TrimDecimalZero(const std::wstring& str) { std::wstring result = str; size_t dotPos = result.find(L'.'); if (dotPos == std::wstring::npos) { return result; } size_t lastNotZero = result.find_last_not_of(L'0'); if (lastNotZero == std::wstring::npos) { return result; } result.erase(lastNotZero + 1); if (!result.empty() && result[result.length() - 1] == L'.') { result.erase(result.length() - 1); } return result; }