Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,102 questions

55,976 answers

573 users

How to find the starting index of all occurrences of a word in a string in Pascal

1 Answer

0 votes
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

}

 



answered Aug 30 by avibootz

Related questions

...