建档
This commit is contained in:
88
source/Tool/Tool_String.cpp
Normal file
88
source/Tool/Tool_String.cpp
Normal file
@@ -0,0 +1,88 @@
|
||||
#include "Tool/Tool_String.h"
|
||||
#include <SDL2/SDL.h>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
#include <iconv.h>
|
||||
#include <regex>
|
||||
#include "Tool_String.h"
|
||||
std::string Tool_toLowerCase(const std::string &str)
|
||||
{
|
||||
std::string result = str;
|
||||
// 使用transform算法遍历字符串并转换为小写
|
||||
std::transform(result.begin(), result.end(), result.begin(),
|
||||
[](unsigned char c)
|
||||
{ return std::tolower(c); });
|
||||
return result;
|
||||
}
|
||||
// GBK 转 UTF-8(基于 SDL2 的 SDL_iconv)
|
||||
std::string Tool_Gbk2Utf8(const std::string &gbk_str)
|
||||
{
|
||||
iconv_t cd = iconv_open("UTF-8", "GBK");
|
||||
if (cd == (iconv_t)-1)
|
||||
{
|
||||
throw std::runtime_error("Failed to open iconv conversion descriptor");
|
||||
}
|
||||
|
||||
size_t in_bytes_left = gbk_str.size();
|
||||
char *in_buf = const_cast<char *>(gbk_str.data());
|
||||
|
||||
// 分配输出缓冲区(GBK转UTF-8后长度最多可能增长到原长的3倍)
|
||||
size_t out_bytes_left = gbk_str.size() * 3 + 1;
|
||||
std::string utf8_str(out_bytes_left, '\0');
|
||||
char *out_buf = &utf8_str[0];
|
||||
|
||||
// 执行转换
|
||||
size_t result = iconv(cd, &in_buf, &in_bytes_left, &out_buf, &out_bytes_left);
|
||||
iconv_close(cd);
|
||||
|
||||
if (result == (size_t)-1)
|
||||
{
|
||||
throw std::runtime_error("Conversion failed!");
|
||||
}
|
||||
|
||||
// 调整字符串大小以去除未使用的空间
|
||||
utf8_str.resize(utf8_str.size() - out_bytes_left);
|
||||
return utf8_str;
|
||||
}
|
||||
|
||||
std::string Tool_RegRealPath(const std::string &Path)
|
||||
{
|
||||
// 检查路径中是否包含"../"
|
||||
if (Path.find("../") == std::string::npos)
|
||||
{
|
||||
return Path;
|
||||
}
|
||||
|
||||
// 正则表达式:匹配形如"xxx/../"的模式
|
||||
// [^/]+ 匹配非斜杠的字符序列(表示目录名)
|
||||
// /../ 匹配"/../"
|
||||
std::regex pattern("[^/]+/\\.\\./");
|
||||
|
||||
std::string processedPath = Path;
|
||||
std::smatch match;
|
||||
|
||||
// 循环处理所有匹配的模式
|
||||
while (std::regex_search(processedPath, match, pattern))
|
||||
{
|
||||
// 替换匹配到的部分(删除"xxx/../")
|
||||
processedPath = std::regex_replace(processedPath, pattern, "", std::regex_constants::format_first_only);
|
||||
}
|
||||
|
||||
return processedPath;
|
||||
}
|
||||
|
||||
std::string Tool_TruncatePath(const std::string &path)
|
||||
{
|
||||
// 查找最后一个 '/' 的位置
|
||||
size_t lastSlashPos = path.find_last_of('/');
|
||||
|
||||
// 如果找到了 '/',返回从开始到该位置(包含)的子串
|
||||
if (lastSlashPos != std::string::npos)
|
||||
{
|
||||
return path.substr(0, lastSlashPos + 1); // +1 是为了包含 '/' 本身
|
||||
}
|
||||
|
||||
// 如果没有找到 '/',返回原字符串(或根据需求返回空)
|
||||
return path;
|
||||
}
|
||||
Reference in New Issue
Block a user