ZetCode

Modula-2 strings

last modified November 26, 2026 Modula-2

Modula-2 has no string type. A string is stored in an array of characters, and the character 0C ends it when it is shorter than the array. The arrays article introduced such character arrays; this article works with them through the Strings module of the Logitech library, which GNU Modula-2 provides for PIM programs, and through procedures of our own.

String variables

A string variable is an ARRAY [0..n] OF CHAR. Indexes from 0 match the open array parameters of the library procedures. Strings.Length returns the number of characters before the terminator, which is usually less than the size of the array.

lengths.mod
MODULE lengths;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;
FROM Strings IMPORT Length;

VAR
  name: ARRAY [0..15] OF CHAR;

BEGIN
  name := "Wirth";
  WriteString(name);
  WriteString(" has ");
  WriteCard(Length(name), 0);
  WriteString(" characters in an array of ");
  WriteCard(HIGH(name) + 1, 0);
  WriteLn;
  WriteString("code of name[5]: ");
  WriteCard(ORD(name[5]), 0);
  WriteLn;
  name := "";
  WriteString("empty string length: ");
  WriteCard(Length(name), 0);
  WriteLn
END lengths.

name has room for 16 characters and holds five. name[5], the element after the last letter, holds the terminator, character code 0. Assigning the empty string "" leaves only a terminator, so the length is 0.

$ gm2 lengths.mod -o lengths
$ ./lengths
Wirth has 5 characters in an array of 16
code of name[5]: 0
empty string length: 0

A string must fit

A string constant may be assigned to a character array that has room for all its characters. The terminator is optional: a constant that fills the array exactly is stored without it.

toolong.mod
MODULE toolong;

VAR
  code: ARRAY [0..3] OF CHAR;

BEGIN
  code := "ABCD";
  code := "Modula"
END toolong.

"ABCD" fills the four elements of code and is accepted. "Modula" has six characters, and the compiler rejects the assignment. Code that reads such a full array must stop at the end of the array as well as at 0C; the library procedures do.

$ gm2 toolong.mod -o toolong
toolong.mod:8:8: error: string constant ‘Modula’ is too large to be assigned to the array ‘code’
    8 |   code := "Modula"
      |   ~~~~~^~~~~~~~~~~
toolong.mod:4:3: error: variable declaration for ‘code’
    4 |   code: ARRAY [0..3] OF CHAR;
      |   ^~~~~~~~~~~~~~~~~~~~~~~~~~

Copying strings with Assign

The assignment a := b needs two arrays of the same type. Strings.Assign(dest, source) copies a string between arrays of any sizes. When the destination is too small, the string is cut off.

copying.mod
MODULE copying;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;
FROM Strings IMPORT Assign, Length;

VAR
  long: ARRAY [0..31] OF CHAR;
  short: ARRAY [0..7] OF CHAR;
  other: ARRAY [0..63] OF CHAR;

PROCEDURE Show(s: ARRAY OF CHAR);
BEGIN
  WriteString("[");
  WriteString(s);
  WriteString("] ");
  WriteCard(Length(s), 0);
  WriteLn
END Show;

BEGIN
  long := "Programming in Modula-2";
  Assign(other, long);
  Show(other);
  Assign(short, long);
  Show(short);
  Assign(long, "Pascal");
  Show(long);
  Assign(short, long);
  Show(short)
END copying.

Show prints a string in brackets, followed by its length. Copying the 23 characters into the eight-element short keeps the first eight. Copying the shorter "Pascal" into long adds a terminator after it, so the rest of the old text is gone.

$ gm2 copying.mod -o copying
$ ./copying
[Programming in Modula-2] 23
[Programm] 8
[Pascal] 6
[Pascal] 6

Joining strings

ConCat(s1, s2, dest) stores s1 followed by s2 in dest. The destination may also be one of the sources, which appends to a string.

joining.mod
MODULE joining;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;
FROM Strings IMPORT Assign, ConCat, Length;

VAR
  first, last: ARRAY [0..15] OF CHAR;
  full: ARRAY [0..31] OF CHAR;
  tag: ARRAY [0..5] OF CHAR;

BEGIN
  Assign(first, "Niklaus");
  Assign(last, "Wirth");
  ConCat(first, " ", full);
  ConCat(full, last, full);
  WriteString(full);
  WriteString(" (");
  WriteCard(Length(full), 0);
  WriteString(" characters)");
  WriteLn;

  ConCat(last, ", ", full);
  ConCat(full, first, full);
  WriteString(full);
  WriteLn;

  ConCat("Modula", "-2", tag);
  WriteString(tag);
  WriteLn;
  ConCat(full, "!", tag);
  WriteString(tag);
  WriteLn
END joining.

The full name is built in two steps: first name and space, then the last name appended to full. The six-element tag shows what happens when the result does not fit: "Modula-2" is cut to Modula, and the second join keeps only the first six characters of Wirth, Niklaus!.

$ gm2 joining.mod -o joining
$ ./joining
Niklaus Wirth (13 characters)
Wirth, Niklaus
Modula
Wirth,

Substrings

Copy(str, index, length, result) copies at most length characters of str, starting at position index, into result.

parts.mod
MODULE parts;

FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Copy;

VAR
  date: ARRAY [0..15] OF CHAR;
  year, month, day: ARRAY [0..3] OF CHAR;
  file: ARRAY [0..31] OF CHAR;
  ext: ARRAY [0..7] OF CHAR;

BEGIN
  date := "2026-11-26";
  Copy(date, 0, 4, year);
  Copy(date, 5, 2, month);
  Copy(date, 8, 2, day);
  WriteString(day);
  WriteString(".");
  WriteString(month);
  WriteString(".");
  WriteString(year);
  WriteLn;

  file := "main.mod";
  Copy(file, 5, 10, ext);
  WriteString("extension: ");
  WriteString(ext);
  WriteLn
END parts.

The year, month and day are cut out of an ISO date and printed in another order. The second call asks for ten characters from position 5 of main.mod; Copy stops at the end of the string, so the extension is mod.

$ gm2 parts.mod -o parts
$ ./parts
26.11.2026
extension: mod

Comparing strings

The operator = does not accept arrays. CompareStr(a, b) returns -1 when a comes first, 0 when the strings are equal and 1 when a comes second.

ordering.mod
MODULE ordering;

FROM InOut IMPORT WriteString, WriteLn, WriteInt;
FROM Strings IMPORT CompareStr;

CONST
  Count = 5;

TYPE
  Name = ARRAY [0..15] OF CHAR;

VAR
  names: ARRAY [1..Count] OF Name;
  first: CARDINAL;
  i: CARDINAL;

PROCEDURE Compare(a, b: ARRAY OF CHAR);
BEGIN
  WriteString(a);
  WriteString(" vs ");
  WriteString(b);
  WriteString(": ");
  WriteInt(CompareStr(a, b), 0);
  WriteLn
END Compare;

BEGIN
  Compare("apple", "banana");
  Compare("pear", "peach");
  Compare("pear", "pear");
  Compare("app", "apple");
  Compare("Zebra", "apple");

  names[1] := "Oberon";
  names[2] := "Modula";
  names[3] := "Pascal";
  names[4] := "Euler";
  names[5] := "Lilith";
  first := 1;
  FOR i := 2 TO Count DO
    IF CompareStr(names[i], names[first]) < 0 THEN
      first := i
    END
  END;
  WriteString("first in order: ");
  WriteString(names[first]);
  WriteLn
END ordering.

The strings are compared character by character by their codes. A prefix comes before the longer string, so app precedes apple, and all upper-case letters come before the lower-case ones, so Zebra precedes apple. The loop keeps the index of the name that comes first so far.

$ gm2 ordering.mod -o ordering
$ ./ordering
apple vs banana: -1
pear vs peach: 1
pear vs pear: 0
app vs apple: -1
Zebra vs apple: -1
first in order: Euler

Insert and Delete in gm2 15.2

The module also exports Insert, Delete and Pos. In GNU Modula-2 15.2 they are not reliable. The program calls the first two.

broken.mod
MODULE broken;

FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Assign, Insert, Delete;

VAR
  s: ARRAY [0..31] OF CHAR;

BEGIN
  Assign(s, "Hello there");
  Insert("big ", s, 6);
  WriteString(s);
  WriteLn;

  Assign(s, "/home/user/notes");
  Delete(s, 0, 11);
  WriteString(s);
  WriteLn;

  Assign(s, "/home/user/notes");
  Delete(s, 5, 5);
  WriteString(s);
  WriteLn
END broken.

Insert should give Hello big there, but it inserts a copy of the string itself instead of the new text. Delete at position 0 appends the rest of the string instead of removing the start; at position 5 it works. Pos, which searches for a substring, works when the substring is present but may crash the program when it is absent. Copy with an index and a length of 0 copies the whole string, for the same reason as Delete. The next three sections write procedures that do these jobs.

$ gm2 broken.mod -o broken
$ ./broken
Hello Hello therethere
/home/user/notesnotes
/home/notes

Removing characters

To remove characters, the rest of the string is moved to the left over them and a new terminator is written. The procedure works on any character array through an open array parameter.

removing.mod
MODULE removing;

FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length;

VAR
  path: ARRAY [0..31] OF CHAR;

PROCEDURE Remove(VAR s: ARRAY OF CHAR; index, count: CARDINAL);
VAR
  len, i: CARDINAL;
BEGIN
  len := Length(s);
  IF (count = 0) OR (index >= len) THEN
    RETURN
  END;
  IF count > len - index THEN
    count := len - index
  END;
  FOR i := index + count TO len - 1 DO
    s[i - count] := s[i]
  END;
  s[len - count] := 0C
END Remove;

BEGIN
  path := "/home/user/notes.txt";
  Remove(path, 0, 11);
  WriteString(path);
  WriteLn;
  Remove(path, 5, 4);
  WriteString(path);
  WriteLn;
  Remove(path, 2, 100);
  WriteString(path);
  WriteLn
END removing.

Remove does nothing when the position lies beyond the end, and it shortens count when fewer characters are left. The FOR loop moves the characters after the removed part, and s[len - count] := 0C ends the shorter string. The first call removes the directory part of the path.

$ gm2 removing.mod -o removing
$ ./removing
notes.txt
notes
no

Finding a substring

A search compares the pattern with the text at every position where it could fit. The function returns whether the pattern was found and passes the position back in a VAR parameter.

finding.mod
MODULE finding;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;
FROM Strings IMPORT Length;

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

PROCEDURE Find(pattern, s: ARRAY OF CHAR; VAR pos: CARDINAL): BOOLEAN;
VAR
  i, j, m, n: CARDINAL;
BEGIN
  m := Length(pattern);
  n := Length(s);
  IF (m = 0) OR (m > n) THEN
    RETURN FALSE
  END;
  FOR i := 0 TO n - m DO
    j := 0;
    WHILE (j < m) AND (s[i + j] = pattern[j]) DO
      INC(j)
    END;
    IF j = m THEN
      pos := i;
      RETURN TRUE
    END
  END;
  RETURN FALSE
END Find;

PROCEDURE Report(pattern: ARRAY OF CHAR);
VAR
  pos: CARDINAL;
BEGIN
  WriteString(pattern);
  IF Find(pattern, text, pos) THEN
    WriteString(" found at ");
    WriteCard(pos, 0)
  ELSE
    WriteString(" not found")
  END;
  WriteLn
END Report;

BEGIN
  text := "modules, procedures and modules again";
  Report("modules");
  Report("procedures");
  Report("again");
  Report("records")
END finding.

For each start position i the WHILE loop counts the matching characters. When all m of them match, the pattern is found. The loop runs only to n - m, so s[i + j] never goes past the end of the text. The function finds the first occurrence: modules is reported at 0, not at 24.

$ gm2 finding.mod -o finding
$ ./finding
modules found at 0
procedures found at 9
again found at 32
records not found

Inserting a string

Inserting is the opposite of removing: the tail of the string moves right to make room, and the new part is copied into the gap. Characters that no longer fit into the array are dropped.

inserting.mod
MODULE inserting;

FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length;

VAR
  line: ARRAY [0..31] OF CHAR;
  tiny: ARRAY [0..7] OF CHAR;

PROCEDURE InsertAt(part: ARRAY OF CHAR; VAR s: ARRAY OF CHAR; index: CARDINAL);
VAR
  len, m, size, i: CARDINAL;
BEGIN
  len := Length(s);
  m := Length(part);
  size := HIGH(s) + 1;
  IF index > len THEN
    index := len
  END;
  i := len;
  WHILE i > index DO
    DEC(i);
    IF i + m < size THEN
      s[i + m] := s[i]
    END
  END;
  i := 0;
  WHILE (i < m) AND (index + i < size) DO
    s[index + i] := part[i];
    INC(i)
  END;
  IF len + m < size THEN
    s[len + m] := 0C
  END
END InsertAt;

BEGIN
  line := "Hello there";
  InsertAt("big ", line, 6);
  WriteString(line);
  WriteLn;
  InsertAt("Oh, ", line, 0);
  WriteString(line);
  WriteLn;
  InsertAt("!", line, 100);
  WriteString(line);
  WriteLn;
  tiny := "abcd";
  InsertAt("XYZ", tiny, 2);
  InsertAt("123", tiny, 1);
  WriteString(tiny);
  WriteLn
END inserting.

The first loop moves the tail, last character first, so nothing is overwritten before it is moved. The second loop copies the new part, and a terminator is written if there is room for one. A position beyond the end appends. The eight-element tiny keeps the first eight characters of a123bXYZcd.

$ gm2 inserting.mod -o inserting
$ ./inserting
Hello big there
Oh, Hello big there
Oh, Hello big there!
a123bXYZ

Reading words

InOut.ReadString skips spaces and line breaks and reads one word, up to the next space or line break. At the end of the input ReadString in gm2 15.2 waits forever instead of setting Done, so the program stops at the word end.

words.mod
MODULE words;

FROM InOut IMPORT WriteString, WriteLn, WriteCard, ReadString;
FROM Strings IMPORT Assign, Length, CompareStr;

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

VAR
  word, first, last, longest: Word;
  count: CARDINAL;

BEGIN
  count := 0;
  ReadString(word);
  WHILE CompareStr(word, "end") # 0 DO
    IF count = 0 THEN
      Assign(first, word);
      Assign(last, word);
      Assign(longest, word)
    ELSE
      IF CompareStr(word, first) < 0 THEN
        Assign(first, word)
      END;
      IF CompareStr(word, last) > 0 THEN
        Assign(last, word)
      END;
      IF Length(word) > Length(longest) THEN
        Assign(longest, word)
      END
    END;
    INC(count);
    ReadString(word)
  END;

  WriteCard(count, 0);
  WriteString(" words");
  WriteLn;
  IF count > 0 THEN
    WriteString("first: ");
    WriteString(first);
    WriteLn;
    WriteString("last: ");
    WriteString(last);
    WriteLn;
    WriteString("longest: ");
    WriteString(longest);
    WriteLn
  END
END words.

The program reads words until end and keeps three of them: the first and the last in alphabetical order, and the longest. The first word read starts all three. Assign copies a word, because first := word works only for arrays of the same type and Assign works for any.

$ gm2 words.mod -o words
$ ./words
the quick brown fox jumps over the lazy dog end
9 words
first: brown
last: the
longest: quick

Next steps

The character handling article looks at the single characters of a string: their classes, codes and case.

Source

The GNU Modula-2 manual

Modula-2 language reference at modula2.org

In this article we have stored strings in character arrays, copied, joined, cut and compared them with the Strings module, written procedures to remove, find and insert text, and read words from the input. The open arrays article covers the ARRAY OF CHAR parameters used by every procedure here, and the arrays article introduces character arrays.

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.