将字符串类型定义为特定格式

Jer*_*dge 0 delphi string casting delphi-7

我想知道是否有一种方法可以在delphi 7中定义一种类型的字符串或类似字符串,它是以特定格式,还是匹配某些规范?例如,我想限定TSizeString它接受值,如类型4x69x12或者甚至2.5x10.75.它应该要求x作为两个数字之间的唯一分隔符.所以不应该像什么x9652-44-6x6-2甚至没有4 x 6.

只是INTEGER + 'x' + INTEGERSINGLE + 'x' + SINGLE.

类似我猜想TFilename的工作方式,标准文件名可能看起来像C:\MyPath\MyFile.txt\\Storage\SomeDir\SomeFile.doc

And*_*and 9

在较新版本的Delphi中,高级记录和运算符重载在这种情况下非常方便:

type
  TSizeString = record
    x, y: single;
  public
    class operator Implicit(const S: string): TSizeString;
    class operator Implicit(const S: TSizeString): string;
  end;

implementation

class operator TSizeString.Implicit(const S: string): TSizeString;
var
  DelimPos: integer;
begin
  DelimPos := Pos('x', S);
  if (DelimPos = 0) or (not TryStrToFloat(Copy(S, 1, DelimPos-1), result.X)) or
    (not TryStrToFloat(Copy(S, DelimPos + 1), result.y)) then
    raise Exception.CreateFmt('Invalid format of size string "%s".', [S]);
end;

class operator TSizeString.Implicit(const S: TSizeString): string;
begin
  result := FloatToStr(S.x) + 'x' + FloatToStr(S.y);
end;
Run Code Online (Sandbox Code Playgroud)

现在你可以做到

procedure TForm1.Button1Click(Sender: TObject);
var
  S: TSizeString;
begin
  S := '20x30';             // works
  ShowMessage(S);
  S := 'Hello World!';      // exception raised
  ShowMessage(S);
end;
Run Code Online (Sandbox Code Playgroud)

在旧版本的Delphi中,您只需编写一个类,或创建一个基本记录来保存您的大小(当然,您可以创建在这些记录和格式化字符串之间进行转换的函数).