ZetCode

Pascal string processing

last modified November 19, 2026 Free Pascal 3.2.2

Most programs that read text have to split it, search it, normalize it, or rebuild it. Pascal provides the primitive operations in the System unit and SysUtils, and StrUtils adds helpers such as PosEx and ReverseString. This article builds a small toolkit with plain strings: a splitter, a word counter, a palindrome test, a reversal, a replace function, and a join function.

Splitting one string

Pos returns the position of the first occurrence of a substring, or 0 when it is absent. Copy(S, Start, Count) returns a piece of a string. Two calls to Copy are enough to divide a string at its first comma: the text before the comma and the text after it.

split1.pas
program split1;
{$mode objfpc}{$H+}

var
  S: string;
  P: Integer;

begin
  S := 'red,green,blue';
  P := Pos(',', S);
  WriteLn(Copy(S, 1, P - 1));
  WriteLn(Copy(S, P + 1, MaxInt));
end.

Pos(',', S) returns 4, the position of the first comma. Copy(S, 1, 3) returns red, and Copy(S, 5, MaxInt) returns everything from position 5 to the end. MaxInt is larger than any string, so the count never cuts the result short. This handles one separator; a general splitter repeats the same step until the text is exhausted.

$ fpc -gl split1.pas
$ ./split1
red
green,blue

Splitting on every delimiter

The general splitter walks the string, finds each occurrence of the separator, and stores the text between separators in a dynamic array. PosEx from StrUtils is like Pos but starts searching at a given position, which avoids rescanning the text that has already been processed.

split2.pas
program split2;
{$mode objfpc}{$H+}

uses StrUtils;

type
  TStringArray = array of string;

function Split(const S, Sep: string): TStringArray;
var
  Start, P, Count: Integer;
begin
  Result := nil;
  Start := 1;
  Count := 0;
  repeat
    P := PosEx(Sep, S, Start);
    if P = 0 then
      P := Length(S) + 1;
    SetLength(Result, Count + 1);
    Result[Count] := Copy(S, Start, P - Start);
    Inc(Count);
    Start := P + Length(Sep);
  until P > Length(S);
end;

var
  Parts: TStringArray;
  I: Integer;

begin
  Parts := Split('red,green,blue,orange', ',');
  WriteLn('parts = ', Length(Parts));
  for I := Low(Parts) to High(Parts) do
    WriteLn(I, ': ', Parts[I]);
end.

The result starts as an empty array: assigning nil to a dynamic array clears it, and it also tells the compiler that the managed result is initialized. The loop searches for the separator starting at Start. When no separator is found, PosEx returns 0 and the code pretends that the separator sits one position past the end, so the final piece is copied as well. The loop ends after that final piece. An empty field between two consecutive separators is preserved as an empty string, which matters when the text is a row of data rather than a sentence.

$ fpc -gl split2.pas
$ ./split2
parts = 4
0: red
1: green
2: blue
3: orange

Counting words

A word counter scans the text one character at a time and builds the current word until it meets a space. When the space arrives, the completed word is counted and printed. The final word is handled after the loop, because the text may not end with a space.

words.pas
program words;
{$mode objfpc}{$H+}

var
  Text, Word: string;
  I, Count: Integer;

begin
  Text := '  the  quick brown   fox jumps over the lazy dog ';
  Count := 0;
  Word := '';
  for I := 1 to Length(Text) do
  begin
    if Text[I] = ' ' then
    begin
      if Word <> '' then
      begin
        Inc(Count);
        WriteLn(Count, ': ', Word);
        Word := '';
      end;
    end
    else
      Word := Word + Text[I];
  end;
  if Word <> '' then
  begin
    Inc(Count);
    WriteLn(Count, ': ', Word);
  end;
  WriteLn('words = ', Count);
end.

Runs of spaces are ignored because an empty Word is not counted. The same loop can be changed to treat punctuation as a separator, or to normalize the word with LowerCase before counting it. For very large texts, appending to a string one character at a time is slow; a TStringBuilder from SysUtils is the efficient alternative.

$ fpc -gl words.pas
$ ./words
1: the
2: quick
3: brown
4: fox
5: jumps
6: over
7: the
8: lazy
9: dog
words = 9

Palindrome check

A palindrome reads the same forward and backward. The test below ignores case, spaces, and punctuation, so a sentence such as A man, a plan, a canal: Panama qualifies. The cleaned string is built first, and then two indices move toward each other.

palindrome.pas
program palindrome;
{$mode objfpc}{$H+}

uses SysUtils;

function IsPalindrome(const S: string): Boolean;
var
  Cleaned: string;
  I: Integer;
  C: Char;
begin
  Cleaned := '';
  for I := 1 to Length(S) do
  begin
    C := UpCase(S[I]);
    if C in ['A'..'Z', '0'..'9'] then
      Cleaned := Cleaned + C;
  end;
  I := 1;
  while (I <= Length(Cleaned) div 2) and
        (Cleaned[I] = Cleaned[Length(Cleaned) - I + 1]) do
    Inc(I);
  Result := I > Length(Cleaned) div 2;
end;

begin
  WriteLn('"A man, a plan, a canal: Panama": ',
          IsPalindrome('A man, a plan, a canal: Panama'));
  WriteLn('"racecar": ', IsPalindrome('racecar'));
  WriteLn('"Pascal":  ', IsPalindrome('Pascal'));
end.

The set test C in ['A'..'Z', '0'..'9'] keeps letters and digits and drops everything else. UpCase only changes ASCII letters; for Unicode text, convert to UnicodeString and use WideUpperCase first. The while loop stops at the first mismatch or when the two indices meet in the middle.

$ fpc -gl palindrome.pas
$ ./palindrome
"A man, a plan, a canal: Panama": TRUE
"racecar": TRUE
"Pascal":  FALSE

Reversing a string

Reversing a string is a simple loop from the last character to the first. StrUtils also provides ReverseString, which returns a new string with the characters in the opposite order. The manual loop is worth knowing because the same pattern reverses an array or a linked list.

reverse.pas
program reverse;
{$mode objfpc}{$H+}

uses StrUtils;

var
  S, R: string;
  I: Integer;

begin
  S := 'Pascal';
  R := '';
  for I := Length(S) downto 1 do
    R := R + S[I];
  WriteLn('manual:  ', R);
  WriteLn('ReverseString: ', ReverseString(S));
end.

The loop starts at Length(S) and counts down to 1, so the first character of the result is the last character of the input. Both lines print lacsaP. For a large string the manual loop reallocates the result repeatedly; ReverseString allocates it once and is faster.

$ fpc -gl reverse.pas
$ ./reverse
manual:  lacsaP
ReverseString: lacsaP

Replacing text

StringReplace from SysUtils replaces every occurrence of a substring. The last argument is a set of options: rfReplaceAll replaces all matches instead of only the first, and rfIgnoreCase compares without case. Without options, only the first match is replaced.

replace.pas
program replace;
{$mode objfpc}{$H+}

uses SysUtils;

var
  S: string;

begin
  S := 'the cat sat on the mat';
  WriteLn(StringReplace(S, 'at', 'og', [rfReplaceAll]));
  WriteLn(StringReplace(S, 'the', 'a', [rfReplaceAll, rfIgnoreCase]));
  WriteLn(StringReplace(S, 'cat', 'dog', []));
end.

The first call changes cat, sat, and mat into cog, sog, and mog. The second replaces both occurrences of the, including the one at the start. The third call passes an empty option set, so only the first cat is replaced; the sentence contains one, and the result is the dog sat on the mat.

$ fpc -gl replace.pas
$ ./replace
the cog sog on the mog
a cat sat on a mat
the dog sat on the mat

Joining the pieces

The inverse of splitting is joining: take an array of strings and place a separator between the elements. A manual Join loop shows the pattern, and Trim removes leading and trailing spaces from each piece. Keeping the separator out of the first element avoids a leading comma.

join.pas
program join;
{$mode objfpc}{$H+}

uses SysUtils;

type
  TStringArray = array of string;

function Join(const Parts: TStringArray; Sep: string): string;
var
  I: Integer;
begin
  Result := '';
  for I := Low(Parts) to High(Parts) do
  begin
    if I > Low(Parts) then
      Result := Result + Sep;
    Result := Result + Parts[I];
  end;
end;

var
  Parts: TStringArray;

begin
  SetLength(Parts, 3);
  Parts[0] := 'red';
  Parts[1] := 'green';
  Parts[2] := 'blue';
  WriteLn(Join(Parts, ', '));
  WriteLn('[', Trim('  padded  '), ']');
end.

Join adds the separator before every element except the first, so the result has exactly two separators for three elements. Trim returns a copy without the spaces at either end; the square brackets in the output make the removal visible. Split and join are often used together: split a line into fields, change one field, then join the fields back into a line.

$ fpc -gl join.pas
$ ./join
red, green, blue
[padded]

Next steps

The formatted output article aligns the fields these routines produce, and the reading input article reads the text that they process. The CSV and text data article applies splitting and joining to files, quoted fields, and typed records.

Source

Free Pascal StrUtils unit

Free Pascal: StringReplace

String on Wikipedia

In this article we split a string at its first comma, wrote a general splitter, counted words, tested palindromes, reversed a string, replaced substrings, and joined an array back into one string. The series continues with CSV and text data in Pascal.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.