How to use strings in Ada?

Oh, ok.
This is actually easy, at least once you understand that Strings are just arrays, unconstrained arrays, but arrays nonetheless.

For illustration-purposes, we’re going to use non-string arrays to explain what’s going on.

Type Vector is Array (Positive range <>) of Natural;

-- Returns a vector from user-input.
Function Prompt return Vector is
  Empty : Constant Vector(2..1):= (others => 1);
  Function Collect( Result : in Vector := Empty ) return Vector is
  Begin
     Ada.Text_IO.Put_Line( "Enter a natural number (Negative to exit): " );
     Declare
        Input : String renames Ada.Text_IO.Get_Line;
        Value : Integer renames Natural'Val( Input );
     Begin
        Return Collect( Result & Value );
     End;
  Exception
     when Constraint_Error => Return Result;
  End Collect;
Begin
  Return Collect;
End Prompt;

Data_Set : Vector:= Prompt;

Now, Data_Set is unconstrained by its subtype and must be constrained by the initialization, which here is Prompt. Since Prompt returns an unconstrained array, it can be any length from 0 to its full index.

So, having constrained Data_Set with the initial value, while it is variable, the size is fixed, meaning you could have (1,4,7,5) and change it to (9,3,7,1), but not (7,7) or (2,3,3,1,8).

The other way to constrain a value would be like Data_Set_2 : Vector(2..7):= (others => 7);, which creates a length-5 vector and filling its elements with 7.

Now, we come to the syntactic sugar for Strings – Strings are merely arrays which have an element which is a character-type (meaning an enumeration having at least one element surrounded by single quotes) – the syntactic sugar allows you to say "Hello" instead of write ('H','e','l','l','o').

Three questions:

  • How do I do this with unbounded strings?
  • How do I do this with bounded strings?
  • Are there any other ways to do this I should be aware of?

I typically do something like:

Function "+"(Right : String) return Ada.Strings.Unbounded_Strings.Unbounded_String renames Ada.Strings.Unbounded_Strings.To_Unbounded_String;
Function "+"(Right : Ada.Strings.Unbounded_Strings.Unbounded_String) return String renames Ada.Strings.Unbounded_Strings.To_String;
--...
X : Unbounded_String:= +"Initial stuff."'
X:= X & (+"Other stuff");
--...
Return Result : String:= +X;

Which you can pretty much do with bounded as well.

1 Like