Searching is one of the tasks of programing that reduces so much of our work and hardship. Today we see a very simple string search sample code…
For second variation/update of this program see this article.
Text search is very easy through a function named PosEx from the strutils unit. The function is given a substring (which part we want to search) and a string (which is the whole text in which we search).
There are many syntax. We would need this syntax:
1 | function PosEx( |
You can test this function with a code like this:
1 | Ret = PosEx('pet', 'I have a big pet dinosaur'); |
Ret would return 14
, as the text ‘pet’ is found on 14th position of the given string.
Quick Tutorial
Start Lazarus.
Create a new Application Project. Project -> New Project -> Application -> OK.
Create a TMemo, a TEdit, and a TButton. Select the TMemo and set its Scrollbars
property to ssAutoVertical
.
Add strutils
to the uses
clause:
1 | uses |
Double click the button and write the following code:
1 | var |
Explanation
1 | Memo1.SelStart := findpos - 1; |
SelStart is 0-based (starts from 0
). PosEx
on the other hand is 1-based (starts from 1
). So findpos
is 1-based. We -1
from findpos
to make it zero-based, for SelStart
.
Run It
Go to Run -> Run or F9. Write something in the memo and then write something in the editbox then click the button.
Downloads
You can download the source code for the tutorial project and executable/EXE files from the links below: