Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - find character a given position/index

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.

like image 579
preahkumpii Avatar asked Jul 18 '12 05:07

preahkumpii


People also ask

How do you find the character in a certain position in a string?

Java String indexOf() MethodThe indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How use POS function in Delphi?

s:='DELPHI PROGRAMMING'; i:=Pos('HI PR',s); In this example, the variable i will return the integer 5, because the specified string begins with the letter H, which is in the fifth position in Source.

How do I remove a character from a string in Delphi?

In Delphi code, Delete removes a substring of Count characters from string or array S , starting with S[Index] . S is a string-type variable. Index and Count are integer-type expressions. If Index is larger than the length of the string or array (or less than 1), no characters are deleted.

What is position in a string?

A string position is a point within a string. It can be compared to an integer (which it is derived from), but it also acts as a pointer within a string so that the preceding and following text can be extracted.


3 Answers

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;
like image 103
Hemant Avatar answered Oct 16 '22 06:10

Hemant


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;
like image 32
Lars Bargmann Avatar answered Oct 16 '22 06:10

Lars Bargmann


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;
like image 2
Danie van Eeden Avatar answered Oct 16 '22 08:10

Danie van Eeden