Name
Pos Function
Syntax
function Pos(const SubStr, Str: string): Integer;
Description
The Pos
function returns the index of the first
occurrence of SubStr
in Str
, or
zero if SubStr
never occurs in
Str
. Pos
is not a real
function.
Tips and Tricks
String indices start at 1.
The search is case sensitive.
Pos
does not handle multibyte characters. You should useAnsiPos
, in theSysUtils
unit, instead ofPos
.
Example
// Environment variables such as PATH store a list of directories
// separated by semicolons. The SplitPath function takes such a string
// as an argument and splits the string into separate filenames.
// The filenames are stored in the FileList argument.
// Note that filenames can contain multibyte characters, so this
// function should call AnsiPos instead of Pos. Nonetheless, it is
// a demonstration of using either function.
procedure SplitPath(const Path: string; FileList: TStrings);
var
Semicolon: Integer;
FileName: string; // First filename in the remaining path
Remaining: string; // The rest of path after the first filename
begin
Remaining := Path;
FileList.BeginUpdate;
try
FileList.Clear;
while Remaining <> '' do
begin
Semicolon := Pos(';', Remaining);
if Semicolon = 0 then
Semicolon := MaxInt;
FileName := Copy(Remaining, 1, Semicolon-1);
Delete(Remaining, 1, Semicolon);
FileList.Add(FileName);
end;
finally
FileList.EndUpdate;
end;
end;
See Also
AnsiString Type, Copy Function, Delete Procedure, Insert Procedure, ShortString Type, String Type |
Get Delphi in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.