Search code examples
delphiunicodedelphi-7

Delphi - check if a Unicode character occurs in a set of characters?


This code works good with Delphi-7 (until Delphi had Unicode support):

Value := edit1.Text[1];
    
if Value in ['м', 'ж'] then ...

'м', 'ж' - cyrillic symbols

But this construction doesn't work with Unicode charachter.
I try a lot of things, but they are doesn't work.
I also tried changing the value types to "Char" and "AnsiChar".

Doesn't work:

const
  MySet : set of WideChar = [WideChar('м'), WideChar('ж')];
begin
  Value := edit1.Text[1];
  if Value in MySet then ...

Doesn't work:

if AnsiChar(Value) in ['м', 'ж'] then ...

Doesn't work:

if CharInSet(Value, ['м', 'ж']) then ...

But this works good:

  if (Value = 'м') or (Value = 'ж') then ...

Whether there is an opportunity to check up UNICODE character by use of a SET in the modern versions of Delphi?
Or should we check each character individually?

My Delphi version is 10.4 update 2 Community Edition


Solution

  • A Delphi set type can only handle a maximum of 256 values, so it cannot be used for handling Unicode characters. For handling Unicode, the System.Character unit provides various methods and helpers.

    For this particular case, there is an IsInArray() character helper you can use. Instead of declaring a set of characters, you will need to declare an array of characters:

    var
      ch: Char;
      a: array of Char;
      s: string;
    begin
      a := ['м', 'ж'];
      s := 'abcж';
      for ch in s do
        if ch.IsInArray(a) then ...
    end;
    

    Note: Delphi XE7 introduced additional language support for initializing and working with dynamic arrays, and square brackets can also be used for simpler array initialization. In the context of above example, ['м', 'ж'] is not a set, but an array of wide characters.