Delphi Basics
AnsiPos
Function
Find the position of one string in another SysUtils unit
 function AnsiPos ( const Needle, HayStack : string ) : Integer;
Description
The AnsiPos function looks for a substring Needle in a string HayStack, returning the position in the string of the first occurence.
 
All Ansi commands support multi-byte and accented characters.
 
If the string is not found, 0 is returned.
 
The search is case sensitive.
Notes
Note that strings start at position 1.

Multi-byte character sets are operating system defined. For example, Oriental versions of Windows uses multi-byte characters to support thier very large set of primitives ('letters').
Related commands
AnsiIndexStr Compares a string with a list of strings - returns match index
AnsiMatchStr Returns true if a string exactly matches one of a list of strings
LastDelimiter Find the last position of selected characters in a string
StrScan Searches for a specific character in a constant string
 
Example code : Find a word in a sentence
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.
 
unit Unit1;
 
interface
 
uses
  SysUtils,   // Unit containing the AnsiPos command
  Forms, Dialogs;
 
type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  end;
 
var
  
Form1: TForm1;
 
implementation
{$R *.dfm} // Include form definitions
 
procedure TForm1.FormCreate(Sender: TObject);

var
  position : Integer;

begin
  // Look for the word 'Cat' in a sentence
  // Note : that this search is case sensitive, so that
  //        the first 'cat' is not matched
  position := AnsiPos('Cat', 'The cat sat on the Cat mat');
  if position = 0
  then ShowMessage('''Cat'' not found in the sentence')
  else ShowMessage('''Cat'' was found at character '+IntToStr(position));
end;
 
end.
Hide full unit code
   'Cat' was found at character 20
 
 
© CodeGear 2006 - 2007. All rights reserved.  |  Home Page