2018年9月26日 星期三
Delphi 執行 Escape編碼及解碼
function Escape(Str: string): string;
var
I: Integer;
w: Word ;
begin
Result := '';
for I := 1 to Length(Str) do
begin
w := Word(Str[I]) ;
if w in [Ord('0')..Ord('9'),Ord('A')..Ord('Z'),Ord('a')..Ord('z')] then
Result := Result + Char(w)
else if w <= 255 then
Result := Result + '%' + IntToHex(w,2)
else
Result := Result + '%u' + IntToHex(w,4);
end;
end;
function Unescape(const Str:String):String;
// Sub Function Begin =======================
function UnescapeUncodeChar(const s:String):WideChar;
var
r:Array [0..1] of Byte;
begin
HexToBin(
PChar(LowerCase(s)),
@r,
SizeOf(r)
);
Result:=WideChar((r[0] shl 8) or r[1]);
end;
function UnescapeAnsiChar(const s:String):Char;
begin
HexToBin(
PChar(LowerCase(s)),
@Result,
SizeOf(Result)
);
end;
// Sub Functionn End ======================
var
I:Integer;
C:Integer;
begin
C:=1;
SetLength(Result,Length(Str));
I:=1;
while I <= Length(Str) do
begin
if Str[I] = '%' then
begin
if (I < Length(Str)) and (Str[I+1]='u') then
begin
Result[C] := UnescapeUncodeChar(
Copy( Str,I+2,4 )
);//Do with '%uxxxx'
Inc(i,6);
end
else
begin
Result[C] := Char(
UnescapeAnsiChar( Copy(Str,I+1,2) )
);//Do with '%xx'
Inc(I,3);
end;
end
else
begin
Result[C] := WideChar(Str[I]);
//
Inc(I);
end;
Inc(C);
end;
SetLength(Result,C-1);
end;
2017年6月21日 星期三
Delphi 判斷字串是否為中文字
可以透過 ByteType函式來判斷字串的內容,藉以辨識每個字節的型態。
var
Str, S1,S2 : String ; // AnsiString
I : integer ;
begin
Str := '12判ew斷dd某一ccc個111' ;
S1 := '' ;
S2 := '' ;
for I := 1 to Length(Str) do
begin
if ByteType(Str,I) = mbSingleByte then
S1 := S1 + Str[I]
else
if ByteType(Str,I) in [mbLeadByte,mbTrailByte] then
S2 := S2 + Str[I] ;
end;
// 輸出結果
S1 --> 12ewddccc111
S2 --> 判斷某一個
end ;
function ByteType(const S: AnsiString; Index: Integer): TMbcsByteType; function ByteType(const S: UnicodeString; Index: Integer): TMbcsByteType;
回傳內容:
mbSingleByte : 單字節字串
mbLeadByte : 雙字節(中文字)字串的第一個字符
mbTrailByte : 雙字節(中文字)字串的第二個字符
範例:var
Str, S1,S2 : String ; // AnsiString
I : integer ;
begin
Str := '12判ew斷dd某一ccc個111' ;
S1 := '' ;
S2 := '' ;
for I := 1 to Length(Str) do
begin
if ByteType(Str,I) = mbSingleByte then
S1 := S1 + Str[I]
else
if ByteType(Str,I) in [mbLeadByte,mbTrailByte] then
S2 := S2 + Str[I] ;
end;
// 輸出結果
S1 --> 12ewddccc111
S2 --> 判斷某一個
end ;
訂閱:
文章 (Atom)