Search code examples
delphicharsetintersectiondelphi-5

Intersection of two strings/ sets


As coming from python I'm looking for something equivalent to this python code (sets) in delphi5:

>>> x = set("Hello")
>>> x
set(['H', 'e', 'l', 'o'])

>>> y = set("Hallo")
>>> y
set(['a', 'H', 'l', 'o'])

>>> x.intersection(y)
set(['H', 'l', 'o'])

Solution

  • var
      a, b, c: set of byte;
    begin
      a := [1, 2, 3, 4];
      b := [3, 4, 5, 6];
      c := a*b;          // c is the intersection of a and b, i.e., c = [3, 4]
    

    But beware:

    var
      a, b, c: set of integer;
    

    will not even compile; instead, you get the 'Sets may have at most 256 elements' error. Please see the documentation for more information on Delphi sets.

    Update

    Sorry, forgot to mention the 'obvious' (from the point of view of a Delphi programmer):

    var
      a, b, c: set of char;
    begin
      a := ['A', 'B', 'C', 'D'];
      b := ['C', 'D', 'E', 'F'];
      c := a*b;          // c is the intersection of a and b, i.e., c = ['C', 'D']
    

    But your chars will all be byte chars -- that is, forget about Unicode (Delphi 5 doesn't support Unicode, so in this case this isn't really a restriction)!