A String is simply an array of characters. The major "catch" with variables of type String is that, when you create a String variable, you must give Ada a way of determining its length - and the variable will stay fixed at that length from then on. There are two major ways for determining a string's length - you can explicitly state how long the string will be, or you can assign the variable a string value (Ada will determine how long the string value is and make the new variable that length).
Ada requires that at least the bounds or the initial string value be given; if both are given, they must match. The "low_bound" is usually 1, though Ada permits the low_bound to be a larger Integer. Here are some examples:
A : String(1..50); -- Variable A holds 50 characters. Question : String := "What is your name?" -- Ada will make String(1..18).
Here's a simplified BNF for declaring String variables:
declare_string_variable ::= list_of_variable_names ":" [ "constant" ] "String" [ bounds ] [ ":=" initial_string_value ] bounds ::= "(" low_bound ".." high_bound ")"Once you have a string, you can use predefined Ada operations on arrays (since a string is simply an array of characters). These include the following:
A(2) := 'f';
B := A;
There are also predefined operations in Text_IO for printing Strings, namely Put and Put_Line. Let's look at an example:
with Text_IO; use Text_IO; procedure String1 is A : String := "Hello"; B : String(1..5); begin B := A; -- B becomes "Hello" A(1) := 'h'; -- A becomes "hello" A(2..3) := A(4..5); -- A becomes "hlolo" A := B(1) & A(2..3) & "ol"; -- A becomes "Hlool" Put_Line(A); A(2..3) := B(2..3); Put_Line(A); end String1;
What is the last line that program String1 will print?
![]() |
![]() |
![]() |
---|
David A. Wheeler (dwheeler@dwheeler.com)
The master copy of this file is at
"http://www.adahome.com/Tutorials/Lovelace/s8s3.htm".