Delphi - find character a given position/index
Asked Answered
S

4

7

I have searched all over for this. In Delphi/Lazarus, given a position, I want to find the character at that position in a different string. I know how to find the position of a character. I need it the other way around: the character at a given position. Thanks in advance.

Stamina answered 18/7, 2012 at 5:25 Comment(0)
T
13

In Delphi, a character in the string can be indexed using the array notation. Just note that first character in string has an index of one.

var
  s: string;
  c: char;
begin
  s := 'Hello';
  c := s[1]; //H
end;
Tunis answered 18/7, 2012 at 5:38 Comment(1)
Note: Characters are 1-based.Fluffy
Z
5

A string can be accessed like an array.

MyString[12] gives you the 12th character in the string. Note : This is 1-index (because the 0th position used to hold the length of the string)

Example :

var
  MyString : String;
  MyChar : Char;
begin
  MyString := 'This is a test';
  MyChar := MyString[4]; //MyChar is 's'
end;
Zoller answered 18/7, 2012 at 5:39 Comment(0)
C
2

This was last answered in 2012, so figured I'd just add an update:

For latest version of Delphi (Currently Tokyo Edition - that run over multiple platforms using FMX framework), the StringHelper class offers a cross platform character index solution. This implementation assumes a 0-based index for all supported platforms.

eg.

var
  myString: String;
  myChar: Char;
begin
  myChar := myString.Chars[0]; 
end;
Chatwin answered 13/9, 2017 at 6:9 Comment(0)
D
0
// 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;
Dachshund answered 14/5, 2019 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.