三層開發中String與WideString的轉換

文章來源:http://blog.csdn.net/yjswjm119/archive/2006/02/18/601807.aspx

// 功能:將 WideString 轉換成 String
function ChWideToAnsi(const StrW: WideString): AnsiString;
var
  nLen: integer;
begin
  Result := StrW;
  if Result <> '' then
  begin
    nLen := WideCharToMultiByte(936, 624, @StrW[1], -1, nil, 0, nil, nil);
    SetLength(Result, nLen - 1);
    if nLen > 1 then
      WideCharToMultiByte(936, 624, @StrW[1], -1, @Result[1], nLen - 1, nil, nil);
  end;
end;

// 功能:將 String 轉換成 WideString
function ChAnsiToWide(const StrA: AnsiString): WideString;
var
  nLen: integer;
begin
  Result := StrA;
  if Result <> '' then
  begin
    nLen := MultiByteToWideChar(936, 1, PChar(@StrA[1]), -1, nil, 0);
    SetLength(Result, nLen - 1);
    if nLen > 1 then
      MultiByteToWideChar(936, 1, PChar(@StrA[1]), -1, PWideChar(@Result[1]), nLen - 1);
  end;
end;

function UTF8ToWideString(const Stream: TStream): WideString;
var
  nLen: Cardinal;
begin
  try
    SetLength(Result, Stream.Size div SizeOf(WideChar) * 3);
    nLen := Utf8ToUnicode(@Result[1], Length(Result),
      Pointer(DWord(TMemoryStream(Stream).Memory) + Stream.Position),
      Stream.Size - Stream.Position);
    SetLength(Result, nLen);
  except
    SetLength(Result, 0);
  end;
end; 

以上的方法,個人認爲主要問題是不同類型的字符串,其長度不同。只要設置對在各種類型下字符串的長度正確就行了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章