【问题标题】:Delphi - find character a given position/indexDelphi - 查找给定位置/索引的字符
【发布时间】:2012-07-18 05:25:12
【问题描述】:

我已经到处搜索了这个。在 Delphi/Lazarus 中,给定一个位置,我想在不同的字符串中找到该位置的字符。我知道如何找到一个角色的位置。我需要它的另一种方式:给定位置的角色。提前致谢。

【问题讨论】:

    标签: delphi pascal lazarus


    【解决方案1】:

    在 Delphi 中,可以使用数组表示法对字符串中的字符进行索引。请注意,字符串中的第一个字符的索引为 1。

    var
      s: string;
      c: char;
    begin
      s := 'Hello';
      c := s[1]; //H
    end;
    

    【讨论】:

    • 注意:字符是从 1 开始的。
    【解决方案2】:

    字符串可以像数组一样被访问。

    MyString[12] 为您提供字符串中的第 12 个字符。 注意:这是 1-index(因为第 0 个位置用于保存字符串的长度)

    例子:

    var
      MyString : String;
      MyChar : Char;
    begin
      MyString := 'This is a test';
      MyChar := MyString[4]; //MyChar is 's'
    end;
    

    【讨论】:

      【解决方案3】:

      最后一次回答是在 2012 年,所以我想添加一个更新:

      对于最新版本的 Delphi(目前为东京版 - 使用 FMX 框架在多个平台上运行),StringHelper 类提供了一个跨平台字符索引解决方案。此实现假定所有支持的平台都有一个从 0 开始的索引。

      例如。

      var
        myString: String;
        myChar: Char;
      begin
        myChar := myString.Chars[0]; 
      end;
      

      【讨论】:

        【解决方案4】:
        // AIndex: 0-based
        function FindCharactedOfStringFromIndex(const AString: String; const AIndex: Integer): Char;
        const
          {$IFDEF CONDITIONALEXPRESSIONS}
            {$IF CompilerVersion >= 24}
            STRING_FIRST_CHAR_INDEX = Low(AString);
            {$ELSE}
            STRING_FIRST_CHAR_INDEX = 1;
            {$ENDIF}
          {$ELSE}
          STRING_FIRST_CHAR_INDEX = 1;
          {$ENDIF}
        var
          index: Integer;
        begin
          index := STRING_FIRST_CHAR_INDEX + AIndex;
          Result := AString[index];
        end;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-12-23
          • 1970-01-01
          • 2012-10-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-12
          相关资源
          最近更新 更多