ZetCode

Modula-2 character handling

last modified November 26, 2026 Modula-2

A CHAR holds one character of the 8-bit character set, and its code is its position in that set. Modula-2 has no library of character classes in PIM; a program tests ranges of codes or uses sets of characters. This article classifies characters, changes their case, turns digits into numbers and reads text one character at a time.

Characters and their codes

ORD gives the code of a character and CHR the character for a code, as the type conversions article showed. The codes of the printable characters follow ASCII.

codes.mod
MODULE codes;

FROM InOut IMPORT Write, WriteString, WriteLn, WriteCard, WriteHex;

VAR
  word: ARRAY [0..15] OF CHAR;
  i: CARDINAL;

BEGIN
  word := "Gm2 4 ever!";
  i := 0;
  WHILE (i <= HIGH(word)) AND (word[i] # 0C) DO
    Write("'");
    Write(word[i]);
    Write("'");
    WriteCard(ORD(word[i]), 5);
    WriteString("  ");
    WriteHex(ORD(word[i]), 2);
    WriteLn;
    INC(i)
  END
END codes.

The loop prints each character of the string with its code in decimal and in hexadecimal. The digits have the codes 48 to 57, the upper-case letters 65 to 90 and the lower-case letters 97 to 122. Within each group the codes are consecutive, which the next sections rely on.

$ gm2 codes.mod -o codes
$ ./codes
'G'   71  47
'm'  109  6d
'2'   50  32
' '   32  20
'4'   52  34
' '   32  20
'e'  101  65
'v'  118  76
'e'  101  65
'r'  114  72
'!'   33  21

Character classes

Because the letters and digits have consecutive codes, a class of characters is tested with two comparisons. Small function procedures give the tests names.

classes.mod
MODULE classes;

FROM InOut IMPORT Write, WriteString, WriteLn;

VAR
  text: ARRAY [0..31] OF CHAR;
  i: CARDINAL;

PROCEDURE IsUpper(ch: CHAR): BOOLEAN;
BEGIN
  RETURN (ch >= 'A') AND (ch <= 'Z')
END IsUpper;

PROCEDURE IsLower(ch: CHAR): BOOLEAN;
BEGIN
  RETURN (ch >= 'a') AND (ch <= 'z')
END IsLower;

PROCEDURE IsDigit(ch: CHAR): BOOLEAN;
BEGIN
  RETURN (ch >= '0') AND (ch <= '9')
END IsDigit;

PROCEDURE IsSpace(ch: CHAR): BOOLEAN;
BEGIN
  RETURN (ch = ' ') OR (ch = 11C) OR (ch = 12C) OR (ch = 15C)
END IsSpace;

BEGIN
  text := "Room 12B, floor 3";
  WriteString(text);
  WriteLn;
  i := 0;
  WHILE (i <= HIGH(text)) AND (text[i] # 0C) DO
    IF IsUpper(text[i]) THEN
      Write('U')
    ELSIF IsLower(text[i]) THEN
      Write('l')
    ELSIF IsDigit(text[i]) THEN
      Write('9')
    ELSIF IsSpace(text[i]) THEN
      Write('_')
    ELSE
      Write('.')
    END;
    INC(i)
  END;
  WriteLn
END classes.

Each character of the text is replaced by a mark of its class: U for upper-case letters, l for lower-case letters, 9 for digits, _ for white space and a dot for anything else. IsSpace lists the tab (11C), the line feed (12C) and the carriage return (15C) by their octal codes.

$ gm2 classes.mod -o classes
$ ./classes
Room 12B, floor 3
Ulll_99U._lllll_9

Classes as sets

A SET OF CHAR constant describes a class in one declaration, and IN tests a character against it. Classes can be combined with the set operators of the sets article.

charsets.mod
MODULE charsets;

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

TYPE
  CharSet = SET OF CHAR;

CONST
  Digits = CharSet{'0'..'9'};
  Letters = CharSet{'A'..'Z', 'a'..'z'};
  Blanks = CharSet{' ', 11C, 12C, 15C};
  Hex = Digits + CharSet{'A'..'F', 'a'..'f'};

PROCEDURE Count(s: ARRAY OF CHAR; class: CharSet): CARDINAL;
VAR
  i, n: CARDINAL;
BEGIN
  n := 0;
  i := 0;
  WHILE (i <= HIGH(s)) AND (s[i] # 0C) DO
    IF s[i] IN class THEN
      INC(n)
    END;
    INC(i)
  END;
  RETURN n
END Count;

PROCEDURE Report(s: ARRAY OF CHAR);
BEGIN
  WriteString(s);
  WriteLn;
  WriteString("  letters ");
  WriteCard(Count(s, Letters), 0);
  WriteString(", digits ");
  WriteCard(Count(s, Digits), 0);
  WriteString(", blanks ");
  WriteCard(Count(s, Blanks), 0);
  WriteString(", hex digits ");
  WriteCard(Count(s, Hex), 0);
  WriteString(", other ");
  WriteCard(Length(s) - Count(s, Letters + Digits + Blanks), 0);
  WriteLn
END Report;

BEGIN
  Report("Room 12B, floor 3");
  Report("colour #C0FFEE")
END charsets.

Hex is the union of the digits and the letters A to F in both cases. Count takes the class as a parameter, so one procedure counts every class. The other characters are those outside the union of letters, digits and blanks; the program subtracts their number from the length of the string.

$ gm2 charsets.mod -o charsets
$ ./charsets
Room 12B, floor 3
  letters 10, digits 3, blanks 3, hex digits 5, other 1
colour #C0FFEE
  letters 11, digits 1, blanks 1, hex digits 7, other 1

Changing case

CAP turns a lower-case letter into upper case and leaves other characters unchanged. PIM has no function for the opposite direction; the distance between 'A' and 'a' in the code table gives it.

case.mod
MODULE case;

FROM InOut IMPORT WriteString, WriteLn;

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

PROCEDURE Lower(ch: CHAR): CHAR;
BEGIN
  IF (ch >= 'A') AND (ch <= 'Z') THEN
    RETURN CHR(ORD(ch) - ORD('A') + ORD('a'))
  END;
  RETURN ch
END Lower;

PROCEDURE ToUpper(VAR s: ARRAY OF CHAR);
VAR
  i: CARDINAL;
BEGIN
  i := 0;
  WHILE (i <= HIGH(s)) AND (s[i] # 0C) DO
    s[i] := CAP(s[i]);
    INC(i)
  END
END ToUpper;

PROCEDURE ToTitle(VAR s: ARRAY OF CHAR);
VAR
  i: CARDINAL;
  start: BOOLEAN;
BEGIN
  start := TRUE;
  i := 0;
  WHILE (i <= HIGH(s)) AND (s[i] # 0C) DO
    IF start THEN
      s[i] := CAP(s[i])
    ELSE
      s[i] := Lower(s[i])
    END;
    start := s[i] = ' ';
    INC(i)
  END
END ToTitle;

BEGIN
  title := "programming in MODULA-2";
  ToUpper(title);
  WriteString(title);
  WriteLn;
  ToTitle(title);
  WriteString(title);
  WriteLn
END case.

Lower moves an upper-case letter by the distance from 'A' to 'a', which is 32 in ASCII. ToUpper applies CAP to every character. ToTitle capitalises the first letter of each word and lowers the rest; a character starts a word when the one before it is a space.

$ gm2 case.mod -o case
$ ./case
PROGRAMMING IN MODULA-2
Programming In Modula-2

Digit values

The value of a digit is its distance from '0'. A number in a string is converted by multiplying the value so far by the base and adding the next digit.

digits.mod
MODULE digits;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

PROCEDURE DigitValue(ch: CHAR): CARDINAL;
BEGIN
  IF (ch >= '0') AND (ch <= '9') THEN
    RETURN ORD(ch) - ORD('0')
  ELSIF (CAP(ch) >= 'A') AND (CAP(ch) <= 'F') THEN
    RETURN ORD(CAP(ch)) - ORD('A') + 10
  END;
  RETURN 99
END DigitValue;

PROCEDURE Parse(s: ARRAY OF CHAR; base: CARDINAL; VAR value: CARDINAL): BOOLEAN;
VAR
  i, d: CARDINAL;
BEGIN
  value := 0;
  i := 0;
  WHILE (i <= HIGH(s)) AND (s[i] # 0C) DO
    d := DigitValue(s[i]);
    IF d >= base THEN
      RETURN FALSE
    END;
    value := value * base + d;
    INC(i)
  END;
  RETURN i > 0
END Parse;

PROCEDURE Show(s: ARRAY OF CHAR; base: CARDINAL);
VAR
  n: CARDINAL;
BEGIN
  WriteString(s);
  WriteString(" in base ");
  WriteCard(base, 0);
  IF Parse(s, base, n) THEN
    WriteString(" is ");
    WriteCard(n, 0)
  ELSE
    WriteString(" is not a number")
  END;
  WriteLn
END Show;

BEGIN
  Show("1978", 10);
  Show("ff", 16);
  Show("C0FFEE", 16);
  Show("101101", 2);
  Show("12x4", 10);
  Show("129", 8)
END digits.

DigitValue handles decimal digits and the hexadecimal letters in both cases, and returns 99 for any other character. Parse rejects a digit that is not smaller than the base, so 9 is not an octal digit, and an empty string. The same loop reads binary, octal, decimal and hexadecimal numbers.

$ gm2 digits.mod -o digits
$ ./digits
1978 in base 10 is 1978
ff in base 16 is 255
C0FFEE in base 16 is 12648430
101101 in base 2 is 45
12x4 in base 10 is not a number
129 in base 8 is not a number

Counting letters

An array indexed by a range of characters counts how often each character occurs. The character itself selects the counter.

letters.mod
MODULE letters;

FROM InOut IMPORT Write, WriteString, WriteLn, WriteCard;

VAR
  count: ARRAY ['A'..'Z'] OF CARDINAL;
  text: ARRAY [0..127] OF CHAR;
  ch: CHAR;
  i, j: CARDINAL;

BEGIN
  text := "Pascal begat Modula-2, and Modula-2 begat Oberon.";
  FOR ch := 'A' TO 'Z' DO
    count[ch] := 0
  END;
  i := 0;
  WHILE (i <= HIGH(text)) AND (text[i] # 0C) DO
    ch := CAP(text[i]);
    IF (ch >= 'A') AND (ch <= 'Z') THEN
      INC(count[ch])
    END;
    INC(i)
  END;

  WriteString(text);
  WriteLn;
  FOR ch := 'A' TO 'Z' DO
    IF count[ch] > 0 THEN
      Write(ch);
      WriteCard(count[ch], 3);
      WriteString(" ");
      FOR j := 1 TO count[ch] DO
        Write('*')
      END;
      WriteLn
    END
  END
END letters.

count is indexed by 'A'..'Z'. CAP folds lower-case letters onto upper-case ones, so the counts ignore case, and the range test skips everything that is not a letter. The second loop prints the letters that occur, each with a bar of stars.

$ gm2 letters.mod -o letters
$ ./letters
Pascal begat Modula-2, and Modula-2 begat Oberon.
A  7 *******
B  3 ***
C  1 *
D  3 ***
E  3 ***
G  2 **
L  3 ***
M  2 **
N  2 **
O  4 ****
P  1 *
R  1 *
S  1 *
T  2 **
U  2 **

Reading characters

InOut.Read reads one character from the input, including spaces and line breaks. At the end of the input it sets Done to FALSE. A line break arrives as the character InOut.EOL.

counting.mod
MODULE counting;

FROM InOut IMPORT Read, Done, EOL, WriteString, WriteLn, WriteCard;

VAR
  ch: CHAR;
  chars, words, lines: CARDINAL;
  inWord: BOOLEAN;

BEGIN
  chars := 0;
  words := 0;
  lines := 0;
  inWord := FALSE;
  Read(ch);
  WHILE Done DO
    INC(chars);
    IF ch = EOL THEN
      INC(lines)
    END;
    IF (ch = ' ') OR (ch = EOL) OR (ch = 11C) THEN
      inWord := FALSE
    ELSIF NOT inWord THEN
      inWord := TRUE;
      INC(words)
    END;
    Read(ch)
  END;
  WriteString("lines ");
  WriteCard(lines, 0);
  WriteString(", words ");
  WriteCard(words, 0);
  WriteString(", characters ");
  WriteCard(chars, 0);
  WriteLn
END counting.

The program counts lines, words and characters like the Unix wc command. inWord remembers whether the previous character belonged to a word; a word is counted when a non-blank character follows a blank one. The loop reads the next character at its end, so Done is tested right after each Read.

$ cat note.txt
Modula-2 came out of the Lilith project.
The workstation and its operating system
were written in the new language.
$ gm2 counting.mod -o counting
$ ./counting < note.txt
lines 3, words 19, characters 116

A ROT13 filter

ROT13 replaces each letter with the letter 13 places further in the alphabet, wrapping around from Z to A. Since the alphabet has 26 letters, applying it twice gives the original text.

rot13.mod
MODULE rot13;

FROM InOut IMPORT Read, Write, Done;

VAR
  ch: CHAR;

PROCEDURE Rotate(c: CHAR): CHAR;
BEGIN
  IF (c >= 'a') AND (c <= 'z') THEN
    RETURN CHR((ORD(c) - ORD('a') + 13) MOD 26 + ORD('a'))
  ELSIF (c >= 'A') AND (c <= 'Z') THEN
    RETURN CHR((ORD(c) - ORD('A') + 13) MOD 26 + ORD('A'))
  END;
  RETURN c
END Rotate;

BEGIN
  Read(ch);
  WHILE Done DO
    Write(Rotate(ch));
    Read(ch)
  END
END rot13.

Rotate turns a letter into its position from 0 to 25, adds 13 modulo 26 and turns the result back into a letter of the same case. Other characters pass unchanged. The program is a filter: it copies its input to its output, so two copies connected by a pipe restore the text.

$ gm2 rot13.mod -o rot13
$ ./rot13 < note.txt
Zbqhyn-2 pnzr bhg bs gur Yvyvgu cebwrpg.
Gur jbexfgngvba naq vgf bcrengvat flfgrz
jrer jevggra va gur arj ynathntr.
$ ./rot13 < note.txt | ./rot13
Modula-2 came out of the Lilith project.
The workstation and its operating system
were written in the new language.

Next steps

The records article groups values of different types, such as a name and a number, into one variable.

Source

The GNU Modula-2 manual

Modula-2 language reference at modula2.org

In this article we have looked at character codes, tested character classes by ranges and by sets, changed the case of letters, converted digits into numbers, counted letters, read the input one character at a time and written a ROT13 filter. The strings article works with whole strings, and the sets article covers sets of characters.

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.