To index a string in Ada, write S(I) where S is a String and I is an Integer in the range S'First .. S'Last. Ada strings are arrays of Character whose index type is Positive, and they are arbitrary-length but fixed once declared, so the index range is part of the value rather than assumed to start at 1. That single detail explains most of what surprises newcomers: a string taken as a slice, a parameter passed by a for loop, or a subtype with a constrained range may not begin at index 1, and element access must respect the bounds actually carried by that particular string object.

The basics are simple; the failure modes are where the learning is. Bounds checking, 'First and 'Last attributes, slice naming, 'Value/'Image, and subtypes like Unbounded_String all behave in specific ways, and mixing them up produces either Constraint_Error at runtime or unexpected Length checks at compile time. The sections below walk through the mechanics, the checks, and the cases where indexing a string is the wrong tool.

The Core Mechanism: Strings Are Constrained Arrays of Character

String is defined in package Standard as an unconstrained array type whose component type is Character and whose index type is Positive. Because it is unconstrained, a String variable, parameter, or function result carries its bounds with it. A declaration like S : String (1 .. 5) := "hello"; creates a string whose valid indices are exactly 1 through 5. Calling S(1) yields 'h', and S(5) yields 'o'.

The important consequence is that there is no universal starting index. The literal "hello" in a declaration with explicit bounds is positioned according to those bounds. If you declare T : String (0 .. 4) := "hello"; then T(0) is 'h' and T(4) is 'o', and T(1) is 'e'. Ada permits bounds that do not start at 1 as long as the range is a valid Positive range, which means indices are positive integers, but the first index can be any positive value. Index 0 is not allowed for a String, because the index subtype is Positive; attempting T : String (0 .. 4) is a compile-time error, not a runtime one. If you need 0-based access, you must build it yourself with an offset or use a different container.

Element indexing uses parentheses, not square brackets: S(I). There is no separate charAt method. Assignment through an index works the same way, S(1) := 'H';, provided the component type is not declared as a constant view. Because Character is a discrete, non-limited type, assignment is straightforward.

Two attributes do most of the everyday work. S'First returns the first valid index and S'Last returns the last. S'Length is S'Last - S'First + 1. For a string of length zero, valid only as a null range or an empty slice, 'First and 'Last have an unusual relationship: 'First is the first index of the range, and 'Last is one less, so S'Last < S'First. Any loop written as for I in S'First .. S'Last therefore iterates zero times on an empty string, which is usually what you want. Writing for I in 1 .. S'Length on an empty or offset string is the classic bug: it indexes positions that may not exist or that point at the wrong characters.

Prerequisites Before You Index

Before touching an element, make sure four things hold.

The string object must exist and be initialized. An uninitialized String variable has undefined contents, so indexing it gives you a Character whose value is meaningless even though the operation is bounds-safe.

The index expression must be of an integer type compatible with the index type, and its value must lie within the bounds of that specific object. Positive, Natural, and plain Integer all convert implicitly in many contexts, but an explicit conversion or a subtype with a constrained range makes intent clearer and can move a bug from runtime to compile time.

If the string comes from a function, you must capture its bounds rather than assume them. A function returning String may return a slice whose lower bound is not 1; storing the result in a variable declared with a different range raises Constraint_Error at the assignment, not at the later index.

If you are indexing a library-provided string-like type, such as Unbounded_String or a Bounded_String from a generic instantiation, direct parentheses indexing is not available unless the package exposes an Element function. Check the package specification rather than assuming array syntax.

Step-by-Step: Indexing a String Safely

1: Declare the string with explicit or inferred bounds. Prefer S : constant String := "hello"; for literals so the compiler infers 1 .. 5, or S : String (1 .. 5) := "hello"; when you need a specific range. Success check: S'First = 1 and S'Last = 5.

2: Decide the index you want and verify it is in range against that object, not a hard-coded number. Use a guard such as if I in S'Range then ... end if; where S'Range is shorthand for S'First .. S'Last. Success check: the branch runs only when the index exists.

3: Read the element with S(I). If you assigned the string or passed it as a parameter, its bounds are preserved, so S(I) is exactly the character at that position. Failure check: a Constraint_Error here means your index was out of range for this object's actual bounds.

4: For a loop over all characters, write for I in S'Range loop ... S(I) ... end loop; or the equivalent for C of S loop, which iterates values directly and avoids index arithmetic entirely. Success check: the loop body executes exactly S'Length times, and zero times for an empty string.

5: If the index comes from user input or a computation, convert and clamp before indexing. S(Integer'Max(I, S'First)) is not a safe clamp by itself when I is below 'First; use an explicit range test. For an offset access into a substring, compute the absolute index as S'First + Offset and confirm the result is within S'Range before use.

6: When extracting a portion rather than a single character, use a slice: S(Lo .. Hi) returns a String with bounds Lo .. Hi and length Hi - Lo + 1. Success check: S(Lo .. Hi)'First = Lo. Slices raise Constraint_Error if Lo > Hi + 1 or Hi > S'Last, so validate endpoints first.

The success criteria are uniform: no exception, and the character equals what you expect at that position. If you want a cheap runtime check beyond exceptions, compare S'Length with the maximum offset you intend to use before the loop.

Working Through Bounds: A Reproducible Example

Consider a fixed string and an off-by-one question. Declare S : String (3 .. 7) := "abcde";. Then S'First = 3, S'Last = 7, S'Length = 5. S(3) = 'a', S(7) = 'e'. S(2) raises Constraint_Error, and so does S(8). A loop for I in S'Range visits 3, 4, 5, 6, 7. A loop for I in 1 .. S'Length visits 1 through 5, and the first index, 1, is out of range, so it fails immediately. This is the arithmetic in one place: the correct lower bound is the object's 'First, never a constant 1.

Now take a slice. T : String := S(4 .. 6); gives T the bounds 4 .. 6, contents "bcd", and length 3. T(4) = 'b'. An expression like T(T'First) is always the first character; T(1) is a constraint error. A function such as function First_Char (X : String) return Character is (X (X'First)); works for any nonempty string regardless of where it starts, and raises Constraint_Error for an empty one because X'First is not a valid index of a null range. A separate guard with if X'Length = 0 then is the standard way to handle that.

Here is the offset calculation made explicit. If you want the fifth character of S in a "0-based" mental model, that is offset 4 from the start, so the absolute index is S'First + 4 = 7, which is 'e'. If you want offset 5, the absolute index is 8, which is out of range. The formula is Index = S'First + Offset, valid exactly when 0 <= Offset < S'Length. Nothing about the formula assumes 1-based indices, which is why it travels safely into Ada 2012 loops and container code.

Characters Versus Strings: Indexing Requires the Right Type

S(I) returns a Character, not a one-character String. That distinction matters the moment you compare or concatenate. S(1) = 'h' is a valid Character comparison. S(1) = "h" is a type mismatch, because "h" is a String of length 1. To get a one-character slice, write S(1 .. 1), which has bounds 1 .. 1 and type String. The reverse direction, turning a Character into a string, is Character'Image or, more idiomatically, the one-element string (1 => C), or C & "" when you want the concatenation form.

This matters for 'Value and 'Image. S(1)'Image yields a quoted string representation, and Character'Pos(S(1)) gives its position in the character set. S(I)'Length does not compile for a Character, because 'Length applies to arrays. If you find yourself writing S(I)'First, that is a sign you meant a slice.

Literals interact with this too. "h" is a String whose bounds are 1 .. 1 when assigned to an unconstrained object in a declaration context, but when it appears as a slice or argument, its bounds are determined by the context. The type checker does not silently convert a string to a character or vice versa, which catches most accidental substitutions at compile time.

Strings From Functions and Parameters: Bounds Are Not Always 1

A function that returns String returns an object with real bounds, and the caller must respect them. A common pattern is a slice-returning function: function Tail (X : String) return String is (X (X'First + 1 .. X'Last)); returns a string whose 'First is one more than the input's. Indexing the result with a literal 1 is wrong unless the input began at 0, which String cannot. Indexing with a variable derived from 'First is right.

When you pass a string to a procedure with an in parameter, bounds are preserved. When you pass it to an out parameter, the formal's subtype may constrain the range, and actual argument bounds must be compatible. A well-known source of confusion is a procedure that declares its formal as S : in String and then loops for I in S'Range; this is correct and adapts to any bounds. Writing for I in 1 .. S'Length in the same procedure is the bug to avoid.

Function results also interact with subtype constraints. If the function's return subtype is String (1 .. 5) but the body returns a slice with bounds 2 .. 6, the return statement raises Constraint_Error at the point of return, not later. That is a good thing: it fails close to the bug. If the return subtype is the unconstrained String, no such check occurs and the bounds travel as-is, which is usually the friendlier interface.

Unbounded and Bounded Strings: No Direct Parentheses

Ada.Strings.Unbounded.Unbounded_String is not an array, so U(I) does not exist. Access goes through functions: Element (U, I) returns the character at position I, and Slice (U, Low, High) returns a String. The convention in this package is that positions are 1-based: Element with index 1 is the first character. Length (U) gives the count. There is no 'First attribute on an Unbounded_String, because it is not an array; the equivalent lower bound is the literal 1, and the upper bound is Length (U). Attempting U'First is a compile-time error.

To index safely, guard with if I in 1 .. Length (U) then. To convert to an array you can index, call To_String (U), which returns a String with bounds 1 .. Length (U). Converting back is To_Unbounded_String. If you need to modify a character in place, Replace_Element (U, I, C) performs a bounds-checked assignment. Beware of implicit conversions: the package requires use Ada.Strings.Unbounded; for the operators, and the automatic conversion of string literals to Unbounded_String only applies in contexts where an Unbounded_String is expected, so Element ("abc", 2) is not valid without an explicit conversion.

Bounded_String from Ada.Strings.Bounded is likewise not an array and follows the same Element/Slice/Length pattern, with a compile-time maximum capacity chosen at generic instantiation. The Length function here reflects the current logical length, not the capacity, so indices beyond the logical length fail even if they are within the capacity.

When Indexing Is the Wrong Tool

Single-character indexing is the correct solution for positional access, scanning, and validation. It is the wrong tool when you are searching for a substring, splitting on a delimiter, or trimming. Those operations need the search and tokenization subprograms in Ada.Strings.Fixed, Ada.Strings.Unbounded, or Ada.Strings.Maps. A hand-rolled for loop that compares characters to find a substring will be slower and more error-prone than Index (Source, Pattern).

Indexing is also a poor fit for transformation. Rebuilding a string character by character into a new fixed array requires knowing the length in advance, and mixing S(I) := ... in place is only safe when the replacement has the same length. For variable-length edits, Unbounded_String with Replace_Slice or Insert/Delete is more honest about the costs. And in any program that handles Unicode text, String indexes Character values from the 256-entry character set; multi-byte or wide characters need Wide_String or Wide_Wide_String, whose index types and element types differ. Indexing a String as if one element were one user-perceived character is a semantic mistake, not a bounds mistake.

One edge case worth internalizing: null ranges. S (1 .. 0) is a valid empty String when the context permits a null range. Its 'First is 1 and its 'Last is 0, and any index into it raises Constraint_Error. Code that computes slices from user-supplied endpoints should allow Lo = Hi + 1 for an empty result and only reject Lo > Hi + 1.

Frequently Asked Questions

Why does S(0) fail when S starts at index 1? Because String's index subtype is Positive, so 0 is not a valid index value at all, and a String whose first index is 1 simply has no element at 0. Use S'First for the first character, or add an offset if your algorithm is zero-based.

Can I change a string's starting index? Not by assignment, and not after the object exists. Bounds are fixed when a constrained object is declared or when a slice is created. You can copy into a differently bounded object, or write a slice, but you cannot rebase an existing array. Re-basing is done with operations that build new strings, not with a loop that mutates existing ones.

What is the difference between S'Length and S'Last? 'Length is a count and 'Last is an index. For a 1-based string of length 5 they coincide numerically at 5, which hides the distinction until a slice starts at a different bound. For a string with bounds 3 .. 7, 'Length is 5 and 'Last is 7.

How do I safely get the last character of a possibly empty string? Test S'Length = 0 first; if not empty, S(S'Last) is the last character. Do not rely on S(S'Length) unless you have confirmed S'First = 1.

Does for C of S need S'Range? No. The of form iterates values, so it never indexes and cannot go out of bounds. It also handles empty strings by iterating zero times, which makes it the most robust loop form for whole-string scans.