In an application I’m working on, I need to convert a set of characters to a string, but I want it to be short, so I want to keep the ranges intact. Now, there may be a better way of doing this, but I had little luck finding a solution online, so I wrote this piece of code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
type TCharSet = set of Char; function CharSetToStr(const CharSet: TCharSet): string; var C, Prev: Char; InRange: Boolean; begin Result := ''; InRange := False; Prev := #0; for C in CharSet do begin if not (Ord(Prev) + 1 = Ord(C)) then begin if InRange then begin InRange := False; Result := Result + '''' + Prev + ''', ''' + C + ''''; end else if Result <> '' then Result := Result + ', ''' + C + '''' else Result := Result + '''' + C + ''''; end else if not InRange then begin InRange := True; Result := Result + '..'; end; Prev := C; end; if InRange then Result := Result + '''' + Prev + ''''; Result := '[' + Result + ']'; end; |
If you input [‘a’..’z’, ‘A’..’Z’, ‘0’..’9′, ‘_’, ‘ ‘, ‘.’], it will print out the string: [‘ ‘, ‘.’, ‘0’..’9′, ‘A’..’Z’, ‘_’, ‘a’..’z’]
In case anyone knows a better way of doing this, let me know in the comments.