How to work with 0-based strings in a backwards compatible way since Delphi XE5?

后端 未结 5 930
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 04:18

I\'m trying to convert my current Delphi 7 Win32 code to Delphi XE5 Android with minimal changes, so that my project can be cross-compiled to Win32 from a range of Delphi versio

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-07 05:01

    All of the RTL's pre-existing functions (Pos(), Copy(), etc) are still (and will remain) 1-based for backwards compatibility. 0-based functionality is exposed via the new TStringHelper record helper that was introduced in XE3, which older code will not be using so nothing breaks.

    The only real gotchas you have to watch out for are things like hard-coded indexes, such as your loop example. Unfortunately, without access to Low/High(String) in older Delphi versions, the only way to write such code in a portable way is to use IFDEFs, eg:

    {$IFDEF CONDITIONALEXPRESSIONS}
      {$IF CompilerVersion >= 24}
        {$DEFINE XE3_OR_ABOVE}
      {$IFEND}
    {$ENDIF}
    
    function StripColor(aText: string): string;
    begin
      for I := {$IFDEF XE3_OR_ABOVE}Low(aText){$ELSE}1{$ENDIF} to {$IFDEF XE3_OR_ABOVE}High(AText){$ELSE}Length(aText){$ENDIF} do
        DoSomething(aText, I);
    end;
    

    Or:

    {$IFDEF CONDITIONALEXPRESSIONS}
      {$IF CompilerVersion >= 24}
        {$DEFINE XE3_OR_ABOVE}
      {$IFEND}
    {$ENDIF}
    
    function StripColor(aText: string): string;
    begin
      for I := 1 to Length(aText) do
      begin
        DoSomething(aText, I{$IFDEF XE3_OR_ABOVE}-(1-Low(AText)){$ENDIF});
      end;
    end;
    

    Conditional Expressions were introduced in Delphi 6, so if you don't need to support version earlier than Delphi 7, and don't need to support other compilers like FreePascal, then you can omit the {$IFDEF CONDITIONALEXPRESSIONS} check.

提交回复
热议问题