nPos Function in Pascal to Find the nth Position in a String

nPos Function in Pascal / Delphi which returns the nth position of character in a string, useful if you want the second or third occurrence.

By Tim TrottLegacy Code • December 11, 2004
nPos Function in Pascal to Find the nth Position in a String

Return the nth position of the search character within a string, a useful function for parsing out file paths or strings separated by constant delimiters.

Usage:

pascal
pos := nPos('/', 'c:/mypath/to/somefile/', 3);

pos = 13

function nPos(C: char; S: string; N: byte): byte;
var
  I, P, K: Integer;
begin
  Result := 0;
  K := 0;
  for I := 1 to N do
  begin
    P := Pos(C, S);
    Inc(K, P);
    if (I = N) and (P > 0) then
    begin
      Result := K;
      Exit;
    end;
    if P > 0 then
      Delete(S, 1, P)
    else
      Exit;
  end;
end;

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

New comments for this post are currently closed.