What is the easiest way to check if a string can safely convert to AnsiString in XE4 and above?

In Delphi XE4 and above, we can write something like:

function TestAnsiCompatible(const aStr: string): Boolean;
begin
end;

stringin Delphi, XE4 is declared as UnicodeString. It may contain a unicode string.

If we do some type conversion:

function TestAnsiCompatible(const aStr: string): Boolean;
var a: AnsiString;
begin
  a := aStr;
  Result := a = aStr;
end;

Some compiler warnings should indicate:

[dcc32 Warning]: W1058 Implicit string cast with potential data loss from 'string' to 'AnsiString'
[dcc32 Warning]: W1057 Implicit string cast from 'AnsiString' to 'string'

Is there a simple and neat way to check if it is fully compatible aStrwith AnsiString? Or we will check the symbol with symbols:

function TestAnsiCompatible(const aStr: string): Boolean;
var C: Char;
begin
  Result := True;
  for C in aStr do begin
    if C > #127 then begin
      Result := False;
      Break;
    end;
  end;
end;
+4
source share
2 answers

All you have to do is reset the warnings:

function TestAnsiCompatible(const aStr: string): Boolean;
var
  a: AnsiString;
begin
  a := AnsiString(aStr);
  Result := String(a) = aStr;
end;

What can be simplified:

function TestAnsiCompatible(const aStr: string): Boolean;
begin
  Result := String(AnsiString(aStr)) = aStr;
end;
+6
source

, String(a) = AnsiString(a), , , . . "" " - 1252" ( , ). , , , 1252.

function StringIs1252(const S: UnicodeString): Boolean;
// returns True if a string is in codepage 1252 (Western European (Windows))
// Cyrillic is 1251
const
  WC_NO_BEST_FIT_CHARS = $00000400;
var
  UsedDefaultChar: BOOL;   // not Boolean!!
  Len: Integer;
begin
  if Length(S) = 0 then
    Exit(True);
  UsedDefaultChar := False;
  Len := WideCharToMultiByte(1252, WC_NO_BEST_FIT_CHARS, PWideChar(S), Length(S), nil, 0, nil, @UsedDefaultChar);
  if Len <> 0 then
    Result := not UsedDefaultchar
  else
    Result := False;
end;

, ansi - , , , # 0.. # 127.

+1

Source: https://habr.com/ru/post/1545557/


All Articles