ZetCode

Ada string processing

last modified November 23, 2026

Text rarely arrives in the shape a program needs. It has leading spaces, mixed case, separators, empty fields, and punctuation that a comparison should ignore. Ada gives a fixed String for text whose length is known and Unbounded_String for text that grows, and the packages Ada.Strings.Fixed and Ada.Characters.Handling supply the searching, trimming, and case routines. This article processes a sentence, a CSV line, an HTTP header, a mixed bag of characters, and a palindrome.

Counting words

The simplest text scan walks the string one character at a time and remembers whether it is currently inside a word. A space ends a word; a non-space after a space starts a new one. The state variable In_Word makes repeated spaces harmless, because only the transition from outside to inside increments the counter.

word_count.adb
with Ada.Text_IO; use Ada.Text_IO;

procedure Word_Count is
   Text    : constant String := "  Ada was designed for safety and long life.  ";
   In_Word : Boolean := False;
   Count   : Natural := 0;
begin
   for C of Text loop
      if C = ' ' then
         In_Word := False;
      elsif not In_Word then
         In_Word := True;
         Count := Count + 1;
      end if;
   end loop;
   Put_Line ("words =" & Natural'Image (Count));
end Word_Count;

The sentence contains eight words. The two leading spaces and the two trailing spaces produce no count of their own, and the punctuation after life is simply part of that word. The loop only recognizes the space character; a tab or a newline would not separate words. The classification section below replaces the space test with Is_Space, which covers all of them.

$ gnatmake -gnat2022 -gnatwa word_count.adb
$ ./word_count
words = 8

Splitting a CSV line

A separator splits a line into fields, and a field can be empty. The next program accumulates characters in an Unbounded_String until it meets a comma, prints the field, and starts a new one. After the loop it prints the last field, which has no comma after it. A fixed String would need a length in advance, so the growing type is the natural choice here.

split_demo.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;

procedure Split_Demo is
   Line : constant String := "red,green,blue,,yellow";

   procedure Show_Fields (Line : String; Separator : Character) is
      Field : Unbounded_String;
   begin
      for C of Line loop
         if C = Separator then
            Put_Line ("[" & To_String (Field) & "]");
            Field := Null_Unbounded_String;
         else
            Append (Field, C);
         end if;
      end loop;
      Put_Line ("[" & To_String (Field) & "]");
   end Show_Fields;
begin
   Show_Fields (Line, ',');
end Split_Demo;

The brackets make the empty fields visible: the two commas in blue,,yellow produce an empty field between them. The same procedure handles a trailing separator, because the final Put_Line then prints the empty string that remains. This splitter does not understand quoted fields, so a comma inside "Smith, John" would still split the line; a CSV reader needs a small state machine that tracks the quote characters.

$ gnatmake -gnat2022 -gnatwa split_demo.adb
$ ./split_demo
[red]
[green]
[blue]
[]
[yellow]

Trimming and changing case

Header lines often carry spaces around the colon and inconsistent case. Trim from Ada.Strings.Fixed removes spaces from the left, the right, or both ends, and To_Lower from Ada.Characters.Handling folds letters. After one trim the colon can be found with Index, and two slices isolate the name and the value.

normalize.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Characters.Handling; use Ada.Characters.Handling;

procedure Normalize is
   Header : constant String := "  Content-Type :  TEXT/HTML  ";
   Clean  : constant String := Trim (Header, Both);
   Colon  : constant Natural := Index (Clean, ":");
   Name   : constant String :=
     To_Lower (Trim (Clean (Clean'First .. Colon - 1), Both));
   Value  : constant String :=
     To_Lower (Trim (Clean (Colon + 1 .. Clean'Last), Both));
begin
   Put_Line ("name  =" & Name);
   Put_Line ("value =" & Value);
end Normalize;

Clean is "Content-Type : TEXT/HTML", so Colon points at the separator. The slice before it still has a space, and the slice after it has two, so each is trimmed again before the case is folded. The result is a name and a value that can be compared with other headers. The program assumes the colon exists: when Index returns zero, Colon - 1 is outside the string and the slice raises Constraint_Error.

$ gnatmake -gnat2022 -gnatwa normalize.adb
$ ./normalize
name  =content-type
value =text/html

Classifying characters

Ada.Characters.Handling answers questions about a single character: Is_Letter, Is_Digit, Is_Space, and several others. A chain of tests can count each group in one pass over the text. The same package also converts a whole string with To_Upper and To_Lower.

classify.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Handling; use Ada.Characters.Handling;

procedure Classify is
   Text : constant String := "Ada 2022: 34 years of safety, 0 crashes?";
   Letters  : Natural := 0;
   Digits_N : Natural := 0;
   Spaces   : Natural := 0;
   Other_N  : Natural := 0;
begin
   for C of Text loop
      if Is_Letter (C) then
         Letters := Letters + 1;
      elsif Is_Digit (C) then
         Digits_N := Digits_N + 1;
      elsif Is_Space (C) then
         Spaces := Spaces + 1;
      else
         Other_N := Other_N + 1;
      end if;
   end loop;

   Put_Line ("letters =" & Natural'Image (Letters));
   Put_Line ("digits  =" & Natural'Image (Digits_N));
   Put_Line ("spaces  =" & Natural'Image (Spaces));
   Put_Line ("others  =" & Natural'Image (Other_N));
   Put_Line (To_Upper (Text));
end Classify;

The four counts add up to the length of the string, so every character falls into exactly one group. The variables cannot be called Digits or Others, because both are reserved words in Ada; the suffixes keep the names legal. The final line shows that To_Upper returns a new string of the same length and leaves the original untouched.

$ gnatmake -gnat2022 -gnatwa classify.adb
$ ./classify
letters = 23
digits  = 7
spaces  = 7
others  = 3
ADA 2022: 34 YEARS OF SAFETY, 0 CRASHES?

Checking palindromes

A palindrome reads the same forwards and backwards, but the comparison should ignore case, spaces, and punctuation. The program first copies the letters and digits into a cleaned string, folded to lower case, and then compares the first character with the last, the second with the second last, and so on. Only half of the string needs to be checked.

palindrome.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Handling; use Ada.Characters.Handling;

procedure Palindrome is

   function Is_Palindrome (Text : String) return Boolean is
      Clean : String (1 .. Text'Length);
      Last  : Natural := 0;
   begin
      for C of Text loop
         if Is_Letter (C) or else Is_Digit (C) then
            Last := Last + 1;
            Clean (Last) := To_Lower (C);
         end if;
      end loop;
      for I in 1 .. Last / 2 loop
         if Clean (I) /= Clean (Last - I + 1) then
            return False;
         end if;
      end loop;
      return True;
   end Is_Palindrome;

begin
   Put_Line ("A man, a plan, a canal: Panama ->" &
             Boolean'Image (Is_Palindrome ("A man, a plan, a canal: Panama")));
   Put_Line ("Was it a car or a cat I saw? ->" &
             Boolean'Image (Is_Palindrome ("Was it a car or a cat I saw?")));
   Put_Line ("GNAT rocks ->" &
             Boolean'Image (Is_Palindrome ("GNAT rocks")));
end Palindrome;

Clean is declared with the length of the original text, so it is always large enough even when every character survives. Last records how much of it is used; the unused tail is never read. The first two sentences differ in case and punctuation but compare equal, while GNAT rocks fails on the first pair of letters. An empty string or a string with a single letter passes the loop and returns true, which is the usual mathematical convention.

$ gnatmake -gnat2022 -gnatwa palindrome.adb
$ ./palindrome
A man, a plan, a canal: Panama ->TRUE
Was it a car or a cat I saw? ->TRUE
GNAT rocks ->FALSE

Next steps

The next article turns numbers into text. It trims the leading space of 'Image, prints integers in other bases and in fixed columns, formats floating-point values, aligns a table, and writes Roman numerals. The strings and unbounded strings articles explain the two string types used here, and hash tables shows how to count words by key rather than by position.

Source

Ada Reference Manual: Fixed-Length String Handling

Ada Reference Manual: Character Handling

GNAT User's Guide

In this article we have counted words in a sentence, split a CSV line into fields including empty ones, normalized a header with trimming and case folding, classified characters with Ada.Characters.Handling, and recognized palindromes while ignoring case, spaces, and punctuation. The strings article covers the indexing and slicing that all of these routines build on.

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 Ada tutorials.