2016-12-03 15 views
1

CP-1253文字列をUnicodeに変換し、逆の変換も実行したいと思います。一部のコードページからUnicodeへの文字列の変換

文字列を保持する2つの変数があるとします(MySource1253MyUnicodeTarget)。

  1. 私はStringMyUnicodeTargetに適している必要がありながら、私は間違っている場合、私を修正してください、MySource1253のための適切な型であることをAnsiStringを推定。

  2. デルファイXEでこれらの変換を行う変換機能がありますか?

+0

どのUnicodeエンコーディングを使用しますか? –

答えて

2

宣言:

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

+0

変換を行うときは、明示的な型キャストを使用して、コンパイラからの「暗黙のキャスト」警告を避けなければなりません。 Unicode <-> Ansi変換は損失の可能性があるため、コンパイラにそのリスクを理解して受け入れさせる必要があります。さらに、RTLには文字列ではなく文字バッファで動作する 'LocaleCharsFromUnicode()'と 'UnicodeFromLocaleChars()'関数もあります。 –

0

RawByteStringToUnicodeStringを呼び出して、最初の引数としてAnsiStringを渡し、2番目の引数としてコードページ(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; 
関連する問題