ZetCode

Ada strings

last modified November 23, 2026

The predefined String type is a sequence of characters with fixed bounds. A literal such as "Ada" has three characters, numbered from 1 to 3, and a variable initialized from it keeps that length for its whole life. This article shows how to index and measure a string, join and cut it, compare strings, and use the library package Ada.Strings.Fixed for searching, trimming, padding, and copying text.

Bounds and indexing

A string is indexed by position, and every position holds one Character. The attributes 'First and 'Last give the bounds, and 'Length gives the number of characters. Indexing starts at 1 for a string literal, but writing the bounds as attributes keeps code correct when a string is later replaced by a slice with different bounds.

index_strings.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Index_Strings is
   Word : constant String := "Ada";
begin
   Put_Line ("word =" & Word);
   Put_Line ("length =" & Natural'Image (Word'Length));
   Put_Line ("first =" & Word (Word'First));
   Put_Line ("last =" & Word (Word'Last));
end Index_Strings;

Word (Word'First) is the character A, and Word (Word'Last) is a. Each character is joined to the preceding string with &, which produces a new string for Put_Line. An index outside the bounds, such as 0 or 4, raises Constraint_Error instead of reading neighbouring memory.

$ gnatmake -gnat2022 -gnatwa index_strings.adb
$ ./index_strings
word =Ada
length = 3
first =A
last =a

Concatenation and slices

The & operator joins two strings, or a string and a character, into a new string whose length is the sum of the parts. A slice selects a contiguous range of positions and is written with the range in parentheses after the string. Slicing copies the selected characters; the original string is unchanged.

concat_slices.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Concat_Slices is
   Word : constant String := "Ada";
   Lang : constant String := Word & " 2022";
   Tail : constant String := Word (2 .. 3);
begin
   Put_Line (Lang);
   Put_Line (Tail);
   Put_Line (Word & '!');
end Concat_Slices;

Lang has eight characters and Tail has the two characters da. The last call joins a string and a character literal, which is why the result ends with an exclamation mark. Because Lang is initialized from an expression, its bounds are those of the produced string, 1 to 8.

$ gnatmake -gnat2022 -gnatwa concat_slices.adb
$ ./concat_slices
Ada 2022
da
Ada!

Comparing strings

Strings compare with the same relational operators as numbers. The comparison walks the two strings from left to right and uses the order of the Character type, so it is case-sensitive: uppercase letters come before lowercase ones. When one string is a prefix of the other, the shorter one is smaller.

compare.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Compare is
   function Before (Left, Right : String) return Boolean is
     (Left < Right);

   function Same (Left, Right : String) return Boolean is
     (Left = Right);

   A : constant String := "apple";
   B : constant String := "banana";
   C : constant String := "apple";
begin
   Put_Line ("a < b =" & Boolean'Image (Before (A, B)));
   Put_Line ("a = c =" & Boolean'Image (Same (A, C)));
   Put_Line ("a = b =" & Boolean'Image (Same (A, B)));
end Compare;

The two small functions wrap the comparisons, so each result is computed as an ordinary Boolean expression and then printed with Boolean'Image. Before returns true because a precedes b, and Same returns true for the two identical strings. The last call compares apple with banana and returns false.

$ gnatmake -gnat2022 -gnatwa compare.adb
$ ./compare
a < b =TRUE
a = c =TRUE
a = b =FALSE

Searching with Index

Ada.Strings.Fixed.Index searches a string for a pattern and returns the position where the pattern starts. If the pattern does not occur, the function returns 0, which is outside every string bound and therefore easy to test. The search is case-sensitive and finds the first occurrence from the left.

find.adb
with Ada.Strings.Fixed;
with Ada.Text_IO;
use Ada.Text_IO;

procedure Find is
   Line : constant String := "the quick brown fox";
   Pos  : constant Natural := Ada.Strings.Fixed.Index (Line, "brown");
   None : constant Natural := Ada.Strings.Fixed.Index (Line, "cat");
begin
   Put_Line ("found at" & Natural'Image (Pos));
   Put_Line ("missing at" & Natural'Image (None));
end Find;

brown begins at position 11, counting from 1, so the first line reports 11. cat is absent, so None is 0. Comparing the result with 0 is the usual way to branch on whether a substring was found, because a real position can never be 0.

$ gnatmake -gnat2022 -gnatwa find.adb
$ ./find
found at 11
missing at 0

Trimming and padding

Ada.Strings.Fixed provides routines that return a new string rather than changing the argument in place. Trim removes spaces from the ends, and the second parameter selects the left end, the right end, or both. Head and Tail take a length and return that many characters, padding with spaces when the source is shorter and cutting when it is longer.

trim_pad.adb
with Ada.Strings;
with Ada.Strings.Fixed;
with Ada.Text_IO;
use Ada.Text_IO;

procedure Trim_Pad is
   Raw : constant String := "  Ada  ";
begin
   Put_Line ("[" & Ada.Strings.Fixed.Trim (Raw, Ada.Strings.Both) & "]");
   Put_Line ("[" & Ada.Strings.Fixed.Head ("Ada", 6) & "]");
   Put_Line ("[" & Ada.Strings.Fixed.Tail ("Ada", 6) & "]");
end Trim_Pad;

The brackets make the spaces visible. Trimming both ends leaves Ada, Head puts the spaces after the word, and Tail puts them before it. Passing Ada.Strings.Left or Ada.Strings.Right to Trim would remove spaces from only one side.

$ gnatmake -gnat2022 -gnatwa trim_pad.adb
$ ./trim_pad
[Ada]
[Ada   ]
[   Ada]

Moving text with Move

Move copies a source string into a target and is the routine to use when the destination already exists. The optional Pad parameter supplies the character that fills the rest of the target when the source is shorter. Overlapping source and target are allowed: Move behaves as if the source were copied to a temporary first, so no characters are lost.

move_text.adb
with Ada.Strings.Fixed;
with Ada.Text_IO;
use Ada.Text_IO;

procedure Move_Text is
   Target : String (1 .. 8) := "........";
begin
   Ada.Strings.Fixed.Move (Source => "hello",
                           Target => Target,
                           Pad    => '*');
   Put_Line (Target);

   Ada.Strings.Fixed.Move (Source => Target (1 .. 5),
                           Target => Target (4 .. 8));
   Put_Line (Target);
end Move_Text;

The first call writes five letters and fills the remaining three positions with asterisks, giving hello***. The second call shifts the first five characters two places to the right; the overlapping range would corrupt a naive character-by-character copy, but Move produces helhello.

$ gnatmake -gnat2022 -gnatwa move_text.adb
$ ./move_text
hello***
helhello

An applied example: initials

The next program combines indexing, comparison, a slice, and a loop. It walks through a sentence, takes every character that starts a word, and stores it in a result string. The condition uses or else so that the check of the previous character is skipped at the first position, where there is no previous character.

initials.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Initials is
   Sentence : constant String := "ada lovelace";
   Result   : String (1 .. 10);
   Count    : Natural := 0;
begin
   for I in Sentence'Range loop
      if I = Sentence'First or else Sentence (I - 1) = ' ' then
         if Sentence (I) /= ' ' then
            Count := Count + 1;
            Result (Count) := Sentence (I);
         end if;
      end if;
   end loop;
   Put_Line (Result (1 .. Count));
end Initials;

The first character is an initial because it starts the sentence. Every later character is an initial when the character before it is a space, and the inner test skips the space itself. The result is al, printed through the slice Result (1 .. Count), because only the filled part of the buffer should be shown.

$ gnatmake -gnat2022 -gnatwa initials.adb
$ ./initials
al

Next steps

A fixed string cannot grow: its length is fixed when the object is created. The next article, unbounded and bounded strings, introduces Ada.Strings.Unbounded for strings that expand as needed and Ada.Strings.Bounded for strings with a declared maximum length. The packages article explains how these library units are organised.

Source

Ada Reference Manual

GNAT User's Guide

AdaCore learning resources

In this article we have indexed and measured fixed strings, joined strings and characters, selected slices, compared strings, searched with Ada.Strings.Fixed.Index, trimmed and padded text, moved overlapping ranges safely, and collected the initials of a sentence. The literals article explains how string literals are written, and the next article removes the fixed-length limit.

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.