To index a string in Ada, name the string, put the position in parentheses, and read or assign one character: S(I). Ada strings are arrays of characters whose index range is directly visible through S'First and S'Last, and a reference to S(I) outside that range raises Constraint_Error. That range rule is the whole game. Unlike C, position 0 is not special; unlike many scripting languages, indexing is not automatically zero-based. A plain String in Ada usually starts at 1, but the language only promises that its bounds are contiguous and ascending, and it lets you declare strings that start anywhere you like.
What "Indexing a String" Means in Ada
In Ada, String is not a primitive with hidden internals. It is a one-dimensional array type whose component type is Character, declared in package Standard roughly as an unconstrained array type indexed by a range of Positive. Because it is an array, every indexing rule you know from arrays applies to strings, and every array attribute works on them: 'First, 'Last, 'Range, 'Length, 'Size, and the rest.
That design explains the two facts that surprise newcomers most. First, indexing a string is not a library call or a method; it is a language-level array operation with compile-time and run-time checks. Second, the lower bound of a string is a property of the value, not of the type. Two variables of the same subtype String can have different bounds at run time, which is why the robust way to write a loop over a string is to iterate over S'Range rather than over a literal 1 .. S'Length.
There is also a terminological distinction worth fixing early. In Ada 95 and later, String refers to Standard.String, a fixed-length unconstrained array type. The containers library provides Ada.Strings.Unbounded.Unbounded_String for growable text, and Ada.Strings.Bounded for a fixed-capacity but variable-length string. Those types do not support S(I) directly, because they are private types wrapping an internal buffer. To index their contents you have to convert to String first, which is a crucial practical detail covered below.
The Prerequisite: Know the Bounds Before You Touch a Position
Before writing S(I), establish three things: that S is a String (or a subtype of it), that the index type of the position you computed is compatible with S's index subtype, and that the position actually falls within S'Range. The first is a type question, the second usually resolves to Positive or Natural, and the third is the one that produces run-time failures.
A convenient mental model is that S'First and S'Last are the honest answer to "where does this string start and end." Never assume S'First = 1, even though string literals and most declared strings begin at 1. If you write a procedure whose parameter is S : in String, the caller may pass a slice such as Name(3 .. 7), whose bounds are 3 and 7. Your procedure's indexing must respect those bounds.
If you are unsure whether a computed index is valid, you have three options: check it explicitly, use a subtype conversion that will be checked, or use a slicing operation that is designed to be safe. Ada's preference is to make the check explicit and let Constraint_Error do the enforcement rather than silently reading adjacent memory.
The Basic Steps for Reading a Character
Here is the smallest complete program that indexes a string, with the expected output noted.
1: Declare a string object with a known value, for example Name : constant String := "Ada Lovelace";. Its bounds are 1 and 12. 2: Choose the position you want. Position 1 is 'A', position 5 is 'L'. 3: Write Name(1) and Name(5) in an expression, for example in a Put_Line call. 4: Compile and run. The program prints A and L.
The exact code shape looks like this:
Success check: the output contains the characters you expected and no exception is raised. Failure mode: if you accidentally wrote Name(0), the program compiles and then raises Constraint_Error at that line during execution, because string literals are indexed from 1 upward and 0 is below Name'First.
The important habit is to treat the position as data, not as a constant. Real programs index with loop counters and computed offsets, and those are where bounds mistakes actually happen.
The Basic Steps for Assigning Through an Index
Indexing on the left side of an assignment mutates the string, provided the string object is not declared constant and the character you assign is of type Character (or a compatible subtype).
1: Declare a mutable string, for example Word : String := "map";. 2: Assign a character to a valid position: Word(1) := 'c';. The string is now "cap". 3: To uppercase a whole string in place, loop over Word'Range and assign To_Upper(Word(I)). 4: Read back Word to confirm the change.
A complete in-place uppercase loop is:
That loop is the canonical Ada idiom for character-by-character string processing. It works no matter what the bounds are, because it iterates over Word'Range rather than 1 .. Word'Length.
One subtlety: you cannot assign a character to a position in a string that was declared as a constant, and you cannot extend a fixed-length string by assigning past its last index. Growing text is the job of Unbounded_String, not of direct indexing.
Indexing Unbounded and Bounded Strings
Unbounded_String is a private type, so U(I) is not legal. You must convert to String before indexing. Package Ada.Strings.Unbounded provides To_String for that.
1: Declare U : Unbounded_String := To_Unbounded_String("hello");. 2: Convert: S : constant String := To_String(U);. S has bounds 1 and 5. 3: Index S(1) normally. 4: After you finish mutating a local string and want the result back in the unbounded value, assign with U := To_Unbounded_String(S);.
For Bounded_String, Ada.Strings.Bounded provides To_String as well, and its result also has bounds starting at 1.
There is a performance note here: converting an unbounded string to String creates a temporary copy, so a loop that does To_String(U)(I) on every iteration re-copies each time — an easy accidental slowdown. Convert once into a local String variable before the loop, or use the Element function if your compiler's standard library version supplies one.
If you only need to inspect one character and the string is short, the copy is harmless. If you are processing megabytes of text, convert once and iterate. That is a legitimate trade-off, not a rule.
Iterating, Slicing, and the Range Idiom
Slicing is the Ada operation that takes a contiguous part of a string by range syntax: S(3 .. 7) returns a String whose lower bound matches the slice start, not necessarily 1. If S := "abcdefg", then S(3 .. 5) is "cde" and its 'First is 3.
This matters because people often expect slices to be re-based. In Ada they are not. A slice keeps the original index range, so S(3 .. 5)'First is 3. Code that assumes a slice starts at 1 will compile and might work on the developer's machine and then fail elsewhere.
The safe pattern for any traversal is:
If you need to jump backward or forward conditionally, use a while loop and manage the index explicitly, with each increment or decrement guarded by a comparison against S'Last or S'First. There is a temptation to use S'Length as a loop bound; it works, but S'Range is clearer and avoids off-by-one risk because it comes from the string itself.
For search, the standard library supplies Ada.Strings.Fixed.Index, which returns 0 when the pattern is not found. That zero sentinel is much older than Ada 2012's Index_Non_Blank-style convenience, so always check the return value against 0 before slicing from it. If you forget, S(Found .. S'Last) can raise Constraint_Error because 0 is out of range, so Ada at least stops you from reading garbage memory.
Worked Example: A Small Character-Counting Utility
Suppose you want to count how many times a character appears in a string, and then report the first and last positions. This exercise touches every indexing concept in a realistic way.
1: Accept the text as a String parameter, not a literal, so the caller can pass any slice. Its bounds come in with it. 2: Loop over Text'Range, incrementing a counter with Count := Count + 1 whenever Text(I) = 'a'. 3: Record First_At and Last_At as Natural values initialized to 0. 4: After the loop, if Count = 0, report that the character was not found; otherwise print the recorded positions.
The arithmetic is reproducible: if Text := "banana", the bounds are 1 and 6, 'a' occurs at positions 2, 4, and 6, so Count = 3 and Last_At = 6. If the caller passes Tail := Text(3 .. 6) (which is "nana"), then Tail'First = 3, and inside the procedure the 'a' positions are 4 and 6, which must be interpreted relative to the original string if the procedure is supposed to report absolute positions. That distinction is exactly the kind of bug that makes bounds handling worth explicit thought: index values are meaningful only with respect to the object they index.
A good sanity check after writing such a utility is to run it on three inputs: an empty string, a one-character string, and a slice. The slice case is the one that exposes the 'First assumption.
Common Mistakes and How to Recognize Them
The first mistake is hard-coding zero-based indexing. If you write S(0) expecting the first character, you get a Constraint_Error. The fix is S(S'First) or just S(1) when you know the literal bounds.
The second mistake is assuming a slice starts at 1. If S(3 .. 5) is passed to a subprogram, S'First is 3, not 1. The fix is to write loops over S'Range.
The third mistake is forgetting that Index returns 0 when nothing matches. Use Found /= 0 before any slice.
The fourth mistake is trying to index an Unbounded_String directly. The compiler rejects U(I) with a type error, not a bounds error. The fix is To_String(U) into a local String first.
The fifth mistake is byte indexing on UTF-8 text. String holds Character values, and Character is 8 bits in the standard profile; a UTF-8 encoded non-ASCII character occupies multiple bytes, so S(I) gives one octet, not one visible glyph. If you slice at an arbitrary byte position in a multi-byte sequence, you can produce invalid UTF-8. For real text processing of non-ASCII data, use a wide or UTF-aware string package and index by code point, or process the byte stream only when you know the encoding and the operation is byte-safe.
Bounds, Constraint_Error, and When to Solve It Differently
Ada's safety guarantee for indexing rests on checks that are enabled by default. This is a genuine strength: the compiler and run-time protect you from buffer overruns that other languages make silent. The cost is that a valid-looking program can raise Constraint_Error at run time if an index is out of bounds, which is why checking your assumptions matters.
A simple, cheap improvement is to use subtypes when you know a string is nonempty. Declaring subtype Name_String is String(1 .. 10); and passing Name_String parameters means the compiler helps enforce length. Subtypes with explicit ranges are also a way to document intent: a String(1 .. 8) for a date field in ISO form is self-describing.
When the data is dynamic, Unbounded_String or the Ada.Containers.Vectors generic vector of characters is a better fit than fixed-length strings. These types provide Element(I) or indexing via Element and handle growth, at the cost of a conversion or an element accessor. The choice is not cosmetic: a fixed String gives you a clean S(I) with predictable bounds, while an unbounded container gives you growth at the cost of one indirection.
Performance is worth a brief note. In typical compiled Ada, a bounds check on every indexed access is usually well-predicted and cheap; removing it requires explicit compiler options and is rarely a good default. If you're writing a tight loop over a large string in a performance-sensitive build, measure before turning off checks. Correctness matters more than a microsecond.
General education, not individual engineering or legal advice. None of this constitutes a guarantee for your specific compiler, standard library version, or safety-certification context; consult your toolchain's documentation and qualified software-engineering support for production-critical code.