String Functions in Pascal

Our program demonstrates various string-related functions in Pascal. Here’s the full source code:

program StringFunctions;

uses
  SysUtils;

procedure PrintLine(const s: string);
begin
  WriteLn(s);
end;

var
  p: procedure(const s: string);

begin
  p := PrintLine;

  // Here's a sample of string functions available in Pascal.
  // Some of these are part of the standard library, while others
  // are from the SysUtils unit.

  p('Contains:  ' + BoolToStr(Pos('es', 'test') > 0, True));
  p('Count:     ' + IntToStr(Length('test') - Length(StringReplace('test', 't', '', [rfReplaceAll]))));
  p('HasPrefix: ' + BoolToStr(Copy('test', 1, 2) = 'te', True));
  p('HasSuffix: ' + BoolToStr(RightStr('test', 2) = 'st', True));
  p('Index:     ' + IntToStr(Pos('e', 'test') - 1));
  p('Join:      ' + StringReplace('a,b', ',', '-', [rfReplaceAll]));
  p('Repeat:    ' + StringOfChar('a', 5));
  p('Replace:   ' + StringReplace('foo', 'o', '0', [rfReplaceAll]));
  p('Replace:   ' + StringReplace('foo', 'o', '0', []));
  p('Split:     ' + '[' + StringReplace('a-b-c-d-e', '-', ' ', [rfReplaceAll]) + ']');
  p('ToLower:   ' + LowerCase('TEST'));
  p('ToUpper:   ' + UpperCase('test'));
end.

To run the program, save it as string_functions.pas and compile it using a Pascal compiler like Free Pascal:

$ fpc string_functions.pas
$ ./string_functions
Contains:   TRUE
Count:      2
HasPrefix:  TRUE
HasSuffix:  TRUE
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      [a b c d e]
ToLower:    test
ToUpper:    TEST

This example demonstrates various string manipulation functions in Pascal. Some key differences from other languages:

  1. Pascal uses 1-based indexing, so the Index function returns 1 for the first occurrence (equivalent to 0 in many other languages).
  2. The StringReplace function is used for both Replace and Join operations.
  3. Pascal doesn’t have a built-in Split function, so we simulated it using StringReplace.
  4. The BoolToStr function is used to convert boolean results to strings.

These functions provide a good starting point for string manipulation in Pascal. For more advanced string operations, you might need to implement custom functions or use additional libraries.