ZetCode

Modula-2 string processing

last modified November 27, 2026 Modula-2

Modula-2 strings are character arrays ended by 0C, and the ISO Strings module provides only the basic operations: copying, extracting, inserting, deleting and finding. Everyday text processing, such as splitting lines into words or fields and trimming blanks, is written on top of them, character by character. This article writes a set of such procedures.

The strings article covers string variables and character handling covers character classes and sets of characters. The examples are compiled with -fiso and use the ISO Strings module.

Counting words

A word is a run of characters that are not separators. Counting words is a matter of counting the places where a word starts.

wordcount.mod
MODULE wordcount;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

TYPE
  CharSet = SET OF CHAR;

CONST
  Separators = CharSet{' ', 11C, ',', '.', ';', ':', '!', '?', '-'};

PROCEDURE CountWords(s: ARRAY OF CHAR): CARDINAL;
VAR
  i, count: CARDINAL;
  inWord: BOOLEAN;
BEGIN
  count := 0;
  inWord := FALSE;
  i := 0;
  WHILE (i <= HIGH(s)) AND (s[i] # 0C) DO
    IF s[i] IN Separators THEN
      inWord := FALSE
    ELSIF NOT inWord THEN
      inWord := TRUE;
      INC(count)
    END;
    INC(i)
  END;
  RETURN count
END CountWords;

PROCEDURE Show(s: ARRAY OF CHAR);
BEGIN
  WriteCard(CountWords(s), 2); WriteString("  '"); WriteString(s);
  WriteString("'"); WriteLn
END Show;

BEGIN
  Show("An old silent pond");
  Show("   a frog jumps into the pond,   splash!  ");
  Show("silence again - and then...");
  Show("");
  Show("  ,,, ")
END wordcount.

Separators is a constant set of characters: blank, tab (11C) and punctuation. inWord remembers whether the previous character belonged to a word. A character that is not a separator after a separator starts a new word, and only then is the counter incremented. Runs of blanks, leading and trailing blanks and lines without any word need no special handling. The loop stops at 0C or at the end of the array, because a string that fills its array has no terminator.

$ gm2 -fiso wordcount.mod -o wordcount
$ ./wordcount
 4  'An old silent pond'
 7  '   a frog jumps into the pond,   splash!  '
 4  'silence again - and then...'
 0  ''
 0  '  ,,, '

Splitting into words

Counting is not enough when the words themselves are needed. The next program splits a line into an array of words.

split.mod
MODULE split;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Strings IMPORT Extract;

TYPE
  CharSet = SET OF CHAR;
  Word = ARRAY [0..31] OF CHAR;

CONST
  Separators = CharSet{' ', 11C, ',', '.', ';', ':', '!', '?'};

VAR
  list: ARRAY [0..9] OF Word;
  count, k: CARDINAL;

PROCEDURE IsSeparator(VAR s: ARRAY OF CHAR; i: CARDINAL): BOOLEAN;
BEGIN
  RETURN (i > HIGH(s)) OR (s[i] = 0C) OR (s[i] IN Separators)
END IsSeparator;

PROCEDURE Split(s: ARRAY OF CHAR; VAR words: ARRAY OF Word; VAR n: CARDINAL);
VAR
  i, start: CARDINAL;
BEGIN
  n := 0;
  i := 0;
  WHILE (i <= HIGH(s)) AND (s[i] # 0C) DO
    IF IsSeparator(s, i) THEN
      INC(i)
    ELSE
      start := i;
      WHILE NOT IsSeparator(s, i) DO INC(i) END;
      IF n <= HIGH(words) THEN
        Extract(s, start, i - start, words[n]);
        INC(n)
      END
    END
  END
END Split;

BEGIN
  Split("  the frog, the pond; the splash!", list, count);
  WriteCard(count, 0); WriteString(" words:"); WriteLn;
  FOR k := 0 TO count - 1 DO
    WriteCard(k, 3); WriteString(" "); WriteString(list[k]); WriteLn
  END
END split.

IsSeparator treats the end of the string like a separator, which ends the last word without a special case. Split skips separators; at the start of a word it remembers the index, moves to the end of the word and copies it with Extract, which takes the source, the start index, the number of characters and the destination. The result is an open array of Word, so the caller decides how many words fit; words that do not fit are dropped.

$ gm2 -fiso split.mod -o split
$ ./split
6 words:
  0 the
  1 frog
  2 the
  3 pond
  4 the
  5 splash

Trimming blanks

Text from files and users often has blanks around it. Trimming removes them from both ends and leaves the inside alone.

trim.mod
MODULE trim;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length, Extract, Assign;

TYPE
  CharSet = SET OF CHAR;

CONST
  Blanks = CharSet{' ', 11C};

VAR
  line: ARRAY [0..63] OF CHAR;

PROCEDURE Trim(VAR s: ARRAY OF CHAR);
VAR
  first, last: CARDINAL;
BEGIN
  first := 0;
  last := Length(s);
  WHILE (first < last) AND (s[first] IN Blanks) DO INC(first) END;
  WHILE (last > first) AND (s[last - 1] IN Blanks) DO DEC(last) END;
  Extract(s, first, last - first, s)
END Trim;

PROCEDURE Show(s: ARRAY OF CHAR);
BEGIN
  Assign(s, line);
  Trim(line);
  WriteString("["); WriteString(s); WriteString("] -> [");
  WriteString(line); WriteString("]"); WriteLn
END Show;

BEGIN
  Show("   lead");
  Show("trail    ");
  Show("in the middle  stays");
  Show("     ");
  Show("")
END trim.

first moves right over leading blanks and last moves left over trailing ones; the two loops never cross, so a string of blanks becomes empty. Extract then copies the part in between to the start of the same string. This is safe, because the source is a value parameter, a copy of the string. The brackets in the output show where the strings begin and end.

$ gm2 -fiso trim.mod -o trim
$ ./trim
[   lead] -> [lead]
[trail    ] -> [trail]
[in the middle  stays] -> [in the middle  stays]
[     ] -> []
[] -> []

Palindromes

A palindrome reads the same backward as forward. In sentences, case, spaces and punctuation are ignored, so the check compares only letters, from both ends towards the middle.

palindrome.mod
MODULE palindrome;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length;

PROCEDURE IsLetter(c: CHAR): BOOLEAN;
BEGIN
  c := CAP(c);
  RETURN (c >= 'A') AND (c <= 'Z')
END IsLetter;

PROCEDURE IsPalindrome(s: ARRAY OF CHAR): BOOLEAN;
VAR
  i, j: CARDINAL;
BEGIN
  i := 0;
  j := Length(s);
  LOOP
    WHILE (i < j) AND NOT IsLetter(s[i]) DO INC(i) END;
    WHILE (j > i) AND NOT IsLetter(s[j - 1]) DO DEC(j) END;
    IF j <= i + 1 THEN
      RETURN TRUE
    END;
    IF CAP(s[i]) # CAP(s[j - 1]) THEN
      RETURN FALSE
    END;
    INC(i);
    DEC(j)
  END
END IsPalindrome;

PROCEDURE Show(s: ARRAY OF CHAR);
BEGIN
  IF IsPalindrome(s) THEN WriteString("yes ") ELSE WriteString("no  ") END;
  WriteString('"'); WriteString(s); WriteString('"'); WriteLn
END Show;

BEGIN
  Show("level");
  Show("Never odd or even");
  Show("A man, a plan, a canal: Panama!");
  Show("Modula-2");
  Show("Step on no pets.");
  Show("")
END palindrome.

i starts at the first character and j just after the last one. Each pass skips characters that are not letters, compares the two letters with CAP, and moves both ends inward. When the ends meet, every pair has matched. No copy of the string is needed, and the empty string counts as a palindrome.

$ gm2 -fiso palindrome.mod -o palindrome
$ ./palindrome
yes "level"
yes "Never odd or even"
yes "A man, a plan, a canal: Panama!"
no  "Modula-2"
yes "Step on no pets."
yes ""

Comma-separated fields

In comma-separated values (CSV), a field that contains a comma is enclosed in double quotes, and a quote inside such a field is written twice. Simply cutting the line at every comma is then wrong.

fields.mod
MODULE fields;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

TYPE
  Field = ARRAY [0..31] OF CHAR;

VAR
  parts: ARRAY [0..7] OF Field;

(* splits s at commas outside double quotes *)
PROCEDURE Fields(s: ARRAY OF CHAR; VAR f: ARRAY OF Field; VAR n: CARDINAL);
VAR
  i, k: CARDINAL;
  quoted: BOOLEAN;
  c: CHAR;
BEGIN
  n := 1; k := 0; i := 0;
  quoted := FALSE;
  f[0][0] := 0C;
  WHILE (i <= HIGH(s)) AND (s[i] # 0C) DO
    c := s[i];
    IF c = '"' THEN
      IF quoted AND (i < HIGH(s)) AND (s[i + 1] = '"') THEN
        IF k < HIGH(f[n - 1]) THEN f[n - 1][k] := '"'; INC(k) END;
        INC(i)
      ELSE
        quoted := NOT quoted
      END
    ELSIF (c = ',') AND NOT quoted AND (n <= HIGH(f)) THEN
      f[n - 1][k] := 0C;
      INC(n); k := 0
    ELSIF k < HIGH(f[n - 1]) THEN
      f[n - 1][k] := c; INC(k)
    END;
    INC(i)
  END;
  f[n - 1][k] := 0C
END Fields;

PROCEDURE Show(line: ARRAY OF CHAR);
VAR
  n, i: CARDINAL;
BEGIN
  WriteString(line); WriteLn;
  Fields(line, parts, n);
  FOR i := 0 TO n - 1 DO
    WriteString("  "); WriteCard(i, 0); WriteString(": [");
    WriteString(parts[i]); WriteString("]"); WriteLn
  END
END Show;

BEGIN
  Show('Bratislava,Slovakia,475503');
  Show('"Vienna, Austria",,2005760');
  Show('"the ""Golden"" City",Prague')
END fields.

Fields copies the line character by character into the current field. quoted is TRUE between quotes; a comma outside quotes ends the field and starts the next one. Two quotes in a row inside a quoted field produce one quote character. A field that is too long is cut, and when the array of fields is full, the remaining commas stay in the last field. Empty fields, such as the second one in the second line, are kept. The string constants are written with single quotes, so that they can contain double quotes.

$ gm2 -fiso fields.mod -o fields
$ ./fields
Bratislava,Slovakia,475503
  0: [Bratislava]
  1: [Slovakia]
  2: [475503]
"Vienna, Austria",,2005760
  0: [Vienna, Austria]
  1: []
  2: [2005760]
"the ""Golden"" City",Prague
  0: [the "Golden" City]
  1: [Prague]

Replacing text

The ISO Strings module finds, deletes and inserts, but has no procedure that replaces every occurrence of a substring. It is written with FindNext, Delete and Insert.

replace.mod
MODULE replace;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length, FindNext, Delete, Insert, Assign;

VAR
  text: ARRAY [0..47] OF CHAR;

PROCEDURE ReplaceAll(VAR s: ARRAY OF CHAR; pattern, by: ARRAY OF CHAR): BOOLEAN;
VAR
  pos, start: CARDINAL;
  found: BOOLEAN;
BEGIN
  start := 0;
  LOOP
    FindNext(pattern, s, start, found, pos);
    IF NOT found THEN
      RETURN TRUE
    END;
    IF Length(s) - Length(pattern) + Length(by) > HIGH(s) + 1 THEN
      RETURN FALSE
    END;
    Delete(s, pos, Length(pattern));
    Insert(by, pos, s);
    start := pos + Length(by)
  END
END ReplaceAll;

PROCEDURE Show(s, pattern, by: ARRAY OF CHAR);
BEGIN
  Assign(s, text);
  WriteString(pattern); WriteString(" -> "); WriteString(by); WriteString(": ");
  IF ReplaceAll(text, pattern, by) THEN
    WriteString(text)
  ELSE
    WriteString("too long: "); WriteString(text)
  END;
  WriteLn
END Show;

BEGIN
  Show("the cat sat on the mat", "at", "og");
  Show("the cat sat on the mat", "the ", "");
  Show("a-b-c", "-", "--");
  Show("one two three", "e", "EEEEEEEEEEEEEEEE")
END replace.

FindNext searches from start and reports the position of the next occurrence. The occurrence is deleted and the replacement inserted in its place. The search then continues after the inserted text, so a replacement that contains the pattern, such as -- for -, is not replaced again. Before each replacement, the procedure checks that the result fits into the array. If it does not, it stops and returns FALSE, with the replacements made so far. The ISO CanInsertAll should make this check, but gm2 15.2 returns the opposite result, so the procedure computes the length itself.

$ gm2 -fiso replace.mod -o replace
$ ./replace
at -> og: the cog sog on the mog
the  -> : cat sat on mat
- -> --: a--b--c
e -> EEEEEEEEEEEEEEEE: too long: onEEEEEEEEEEEEEEEE two thrEEEEEEEEEEEEEEEEe

A text module

Trimming and splitting are needed in almost every program that reads text, so they go into a Text module. The program reads a CSV file from standard input and prints it as a table.

Text.def
DEFINITION MODULE Text;

TYPE
  Field = ARRAY [0..31] OF CHAR;

PROCEDURE Trim(VAR s: ARRAY OF CHAR);
PROCEDURE Split(s: ARRAY OF CHAR; sep: CHAR;
                VAR f: ARRAY OF Field; VAR n: CARDINAL);

END Text.

Split now takes the separator as a parameter and trims each field. The Field type is exported, so that clients can declare arrays of fields.

Text.mod
IMPLEMENTATION MODULE Text;
FROM Strings IMPORT Length, Extract;

TYPE
  CharSet = SET OF CHAR;

CONST
  Blanks = CharSet{' ', 11C};

PROCEDURE Trim(VAR s: ARRAY OF CHAR);
VAR
  first, last: CARDINAL;
BEGIN
  first := 0;
  last := Length(s);
  WHILE (first < last) AND (s[first] IN Blanks) DO INC(first) END;
  WHILE (last > first) AND (s[last - 1] IN Blanks) DO DEC(last) END;
  Extract(s, first, last - first, s)
END Trim;

PROCEDURE Split(s: ARRAY OF CHAR; sep: CHAR;
                VAR f: ARRAY OF Field; VAR n: CARDINAL);
VAR
  i, start, len: CARDINAL;
BEGIN
  n := 0;
  start := 0;
  len := Length(s);
  FOR i := 0 TO len DO
    IF ((i = len) OR (s[i] = sep)) AND (n <= HIGH(f)) THEN
      Extract(s, start, i - start, f[n]);
      Trim(f[n]);
      INC(n);
      start := i + 1
    END
  END
END Split;

END Text.

Trim is the procedure from the trimming section. Split walks through the string up to and including the position of the terminator, so the end of the string closes the last field like a separator. Unlike Fields, it does not handle quotes.

table.mod
MODULE table;
FROM STextIO IMPORT ReadString, SkipLine, WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM SIOResult IMPORT ReadResult, ReadResults;
FROM Strings IMPORT Length, Capitalize;
FROM Text IMPORT Field, Split;

VAR
  line: ARRAY [0..127] OF CHAR;
  f: ARRAY [0..2] OF Field;
  n, cities: CARDINAL;
  header: BOOLEAN;

PROCEDURE Column(s: ARRAY OF CHAR; width: CARDINAL; right: BOOLEAN);
VAR
  i: CARDINAL;
BEGIN
  IF NOT right THEN WriteString(s) END;
  FOR i := Length(s) + 1 TO width DO WriteString(" ") END;
  IF right THEN WriteString(s) END
END Column;

BEGIN
  cities := 0;
  header := TRUE;
  LOOP
    ReadString(line);
    IF (ReadResult() = endOfInput) AND (Length(line) = 0) THEN EXIT END;
    SkipLine;
    Split(line, ',', f, n);
    IF n = 3 THEN
      IF header THEN
        Capitalize(f[0]); Capitalize(f[1]); Capitalize(f[2]);
        header := FALSE
      ELSE
        INC(cities)
      END;
      Column(f[0], 12, FALSE); Column(f[1], 10, FALSE);
      Column(f[2], 12, TRUE); WriteLn
    ELSIF Length(line) > 0 THEN
      WriteString("skipped: "); WriteString(line); WriteLn
    END
  END;
  WriteCard(cities, 0); WriteString(" cities"); WriteLn
END table.

The main loop reads every line as in the reading input article. A line with three fields becomes a row of the table; the first one is the header and is turned into capitals with Capitalize. Column pads a field to a fixed width, on the right for text and on the left for numbers. Empty lines are ignored, and a line without the commas is reported. The input file has extra blanks around many fields.

$ cat cities.csv
 name ,country,  population
Bratislava , Slovakia,475503
  Kosice,Slovakia ,  229040
Brno,Czechia,  402739

Graz,   Austria,  291134
Linz Austria 210165
Debrecen ,Hungary,199520
$ gm2 -fiso -c Text.mod
$ gm2 -fiso table.mod Text.o -o table
$ ./table < cities.csv
NAME        COUNTRY     POPULATION
Bratislava  Slovakia        475503
Kosice      Slovakia        229040
Brno        Czechia         402739
Graz        Austria         291134
skipped: Linz Austria 210165
Debrecen    Hungary         199520
5 cities

Source

The GNU Modula-2 manual

The ISO libraries in GNU Modula-2

In this article we have counted words, split lines into words, trimmed blanks, recognised palindromes, parsed comma-separated fields with quotes, replaced substrings and collected the most useful procedures in a module that turns a CSV file into a table. The strings article covers the basics of Modula-2 strings, and the files article reads and writes text files.

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 Modula-2 tutorials.