[UE4] 使用C++解码(Decode)URL中的中文字符
世欺子
2020年09月23日 22:13
收录于文集
共14篇

今天朋友发来一个需求,要解码一串URL中的中文字符(变量类型:Name),最终在UE4里解析为中文字符并显示

图:@时辰不死于背锅

比如“2020%E6%96%B0%E5%B9%B4%E5%BF%AB%E4%B9%90”要解码成“2020新年快乐”

其实Javascript或者Python写很容易,因为自带解码器或者很轻松调用第三方库

但朋友的需求是做成UE4函数并可以在蓝图中调用👇

抱着试试看的态度找到了前人写的轮子:https://blog.csdn.net/nanjunxiao/article/details/9974593?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

不过这个是纯基于C++的,要转成UE4可以调用的FString还要经过些许步骤,下面是步骤复现:

1.创建一个基于C++的UE4工程,并创建一个名为BF_DecodeChinese的蓝图函数库(CPP)

2.找到对应的.h文件和.cpp文件,键入如下代码:

BF_DecodeChinese.h:

#pragma once #include "CoreMinimal.h" #include "Kismet/BlueprintFunctionLibrary.h" #include "BF_DecodeChinese.generated.h" /**  *   */ UCLASS() class DECODECHINESE_API UBF_DecodeChinese : public UBlueprintFunctionLibrary { GENERATED_BODY() UFUNCTION(BlueprintCallable, meta = (DisplayName = "Decode Chinese Character", Keywords = "Decode Chinese Character"), Category = "Encoding and Decoding") static FString DecodeChineseCharacter(const FString&decodingString); };

BF_DecodeChinese.cpp:

#include "BF_DecodeChinese.h" #include <string> #include <iostream> using namespace std; FString UBF_DecodeChinese::DecodeChineseCharacter(const FString&decodingString) { //FString to std::string std::string cstr(TCHAR_TO_UTF8(*decodingString)); //Note from RFC1630:  "Sequences which start with a percent sign //but are not followed by two hexadecimal characters (0-9,A-F) are reserved //for future extension" const unsigned char *ptr = (const unsigned char *)cstr.c_str(); string ret; ret.reserve(cstr.length()); for (; *ptr; ++ptr) { if (*ptr == '%') { if (*(ptr + 1)) { char a = *(ptr + 1); char b = *(ptr + 2); if (!((a >= 0x30 && a < 0x40) || (a >= 0x41 && a < 0x47))) continue; if (!((b >= 0x30 && b < 0x40) || (b >= 0x41 && b < 0x47))) continue; char buf[3]; buf[0] = a; buf[1] = b; buf[2] = 0; ret += (char)strtoul(buf, NULL, 16); ptr += 2; continue; } } if (*ptr == '+') { ret += ' '; continue; } ret += *ptr; } //std::string to FString FString result = FString(UTF8_TO_TCHAR(ret.c_str())); return result; }

其中代码主体部分借鉴了上面提到的解码算法

在此前有一个将UE4的FString转化成std::string的过程,其中用到了TCHAR_TO_UTF8

最终输出以前一定要转回来,不然即便没报错,也会输出一堆???

就像下面这样:

成功输出后的截图:

如果需要用到这个小功能而不想自己码代码的话,可以在我的技术交流群自取工程文件(版本UE 4.24),群号:822834246

今天的分享就到这里