我想將CP-1253字符串轉換爲Unicode,並且也執行相反的轉換。將字符串從某些代碼頁轉換爲Unicode
假設我有兩個變量持有字符串,MySource1253
和MyUnicodeTarget
。
我相信
AnsiString
成爲MySource1253
合適的類型,而String
應該MyUnicodeTarget
是合適的,請糾正我,如果我錯了。Delphi XE中是否有一些功能可以將這些轉換從一個轉換爲另一個,反之亦然?
我想將CP-1253字符串轉換爲Unicode,並且也執行相反的轉換。將字符串從某些代碼頁轉換爲Unicode
假設我有兩個變量持有字符串,MySource1253
和MyUnicodeTarget
。
我相信AnsiString
成爲MySource1253
合適的類型,而String
應該MyUnicodeTarget
是合適的,請糾正我,如果我錯了。
Delphi XE中是否有一些功能可以將這些轉換從一個轉換爲另一個,反之亦然?
聲明:本
type
GreekString = type Ansistring(1253);
並在它們之間進行轉換,只需使用下面的代碼:
var
UnicodeStr: string;
GreekStr: GreekString;
begin
UnicodeStr := 'This is a test.'; // Unicode string
GreekStr := GreekString(UnicodeStr); // ...converted to 1253
GreekStr := 'This is a test.'; // Greek string
UnicodeStr := string(GreekStr); // ...converted to Unicode
end;
參見:How can I convert string encoded with Windows Codepage 1251 to a Unicode string。
當進行轉換時,你必須使用顯式的類型轉換來避免編譯器的「隱式轉換」警告。 Unicode <-> Ansi轉換可能有損耗,因此您必須告訴編譯器您瞭解並接受該風險。另外,RTL還有'LocaleCharsFromUnicode()'和'UnicodeFromLocaleChars()'函數,它們在字符緩衝區而不是字符串上運行。 –
只需調用RawByteStringToUnicodeString並將您的AnsiString作爲第一個參數,並將代碼頁(1253)作爲第二個參數傳遞。
MyUnicodeString := RawByteStringToUnicodeString(MyAnsiString, 1253);
這裏是從AnsiString(RawByteString)轉換爲Unicode和返回的函數。它們是Win32 MultiByteToWideChar/WideCharToMultiByte的安全包裝。
uses
Windows, Math;
function RawByteStringToUnicodeString(const S: RawByteString; CP: Integer): UnicodeString;
var
P: PAnsiChar;
pw: PWideChar;
I, J: Integer;
begin
Result := '';
if S = '' then
Exit;
if CP = CP_UTF8 then
begin
// UTF8
Result := UTF8ToUnicodeString(S);
Exit;
end;
P := @S[1];
I := MultiByteToWideChar(CP, 0, P, Length(S), nil, 0);
if I <= 0 then
Exit;
SetLength(Result, I);
pw := @Result[1];
J := MultiByteToWideChar(CP, 0, P, Length(S), pw, I);
if I <> J then
SetLength(Result, Min(I, J));
end;
function UnicodeStringToRawByteString(const w: UnicodeString; CP: Integer): RawByteString;
var
P: PWideChar;
I, J: Integer;
begin
Result := '';
if w = '' then
Exit;
case CP of
CP_UTF8:
begin
// UTF8
Result := UTF8Encode(w);
Exit;
end;
CP_UNICODE_LE:
begin
// Unicode codepage
CP := CP_ACP;
end;
end;
P := @w[1];
I := WideCharToMultibyte(CP, 0, P, Length(w), nil, 0, nil, nil);
if I <= 0 then
Exit;
SetLength(Result, I);
J := WideCharToMultibyte(CP, 0, P, Length(w), @Result[1], I, nil, nil);
if I <> J then
SetLength(Result, Min(I, J));
SetCodePage(Result, CP, False);
end;
你想使用哪種Unicode編碼。你有什麼樣的表格數據。 –