我有一个字符串'MIROKU'
。我想将此字符串转换为'%82l%82h%82q%82n%82j%82t'
。以下是我用于转换的当前功能:
function MyEncode(const S: string; const CodePage: Integer): string;
var
Encoding: TEncoding;
Bytes: TBytes;
b: Byte;
sb: TStringBuilder;
begin
Encoding := TEncoding.GetEncoding(CodePage);
try
Bytes := Encoding.GetBytes(S);
finally
Encoding.Free;
end;
sb := TStringBuilder.Create;
try
for b in Bytes do begin
sb.Append('%');
sb.Append(IntToHex(b, 2));
end;
Result := sb.ToString;
finally
sb.Free;
end;
end;
MyEncode('MIROKU', 932)
返回'%82%6C%82%68%82%71%82%6E%82%6A%82%74'
。我不指望这个结果。我期待'%82l%82h%82q%82n%82j%82t'
。有没有正确转换它的功能?
答案 0 :(得分:1)
你所看到的是正确的,而不是你所期待的。例如,%6C
是l
的ascii表示。所以你可以尝试这样的事情:
function MyEncode(const S: string; const CodePage: Integer): string;
var
Encoding: TEncoding;
Bytes: TBytes;
b: Byte;
sb: TStringBuilder;
begin
Encoding := TEncoding.GetEncoding(CodePage);
try
Bytes := Encoding.GetBytes(S);
finally
Encoding.Free;
end;
sb := TStringBuilder.Create;
try
for b in Bytes do begin
if (b in [65..90]) or (b in [97..122]) then
begin
sb.Append( char(b)); // normal ascii
end
else
begin
sb.Append('%');
sb.Append(IntToHex(b, 2));
end;
end;
Result := sb.ToString;
finally
sb.Free;
end;
end;
或者你可以保持原样!