program FindOccurrences;
{
This program finds all starting indices of a word inside a larger string.
It uses the built‑in Pos function, which returns the 1‑based index of the
next occurrence of a substring. We loop until Pos returns 0 (no more matches).
}
{
Find and print all starting indices of a word inside a text.
The algorithm:
- Use Pos to locate the next occurrence.
- Print the index.
- Continue searching from the next character.
}
procedure FindAllOccurrences(const text, word: string);
var
index, startPos: Integer;
begin
if word = '' then
Exit; { Searching for an empty word is meaningless }
startPos := 1; { Start scanning from the beginning }
while True do
begin
index := Pos(word, Copy(text, startPos, Length(text) - startPos + 1));
if index = 0 then
Break; { No more occurrences }
{
Pos returns an index relative to the substring we passed,
so we convert it to an absolute index in the original text.
}
WriteLn(startPos + index - 1);
{
Move forward by one character to continue searching.
This also allows detection of overlapping matches.
}
startPos := startPos + index;
end;
end;
var
text, word: string;
begin
text := 'the quick brown fox jumps over the lazy dog. the fox is clever.';
word := 'the';
WriteLn('Text: ', text);
WriteLn('Word: "', word, '"');
WriteLn;
WriteLn('Occurrences at indices:');
FindAllOccurrences(text, word);
end.
{
run:
Text: the quick brown fox jumps over the lazy dog. the fox is clever.
Word: "the"
Occurrences at indices:
1
32
46
}