String arrays in Ada
I have a program in Ada95 where I have to create an array of strings. This array can contain variable length strings.
Example: I have declared an array in which all indices can store strings of size 50. When I assign a smaller string to the above array, I get a "Constraint error".
code:
procedure anyname is
input_array : array(1..5) of String(1..50);
begin
input_array(1):="12345";
end anyname;
I tried to create an array of Unbounded_Strings. But that doesn't work either. Can anyone tell me how to store this "12345" in the above array of strings?
source to share
If you are using Unbounded_String
, you cannot directly pass a string literal. String literals can be of type String
, Wide_String
or Wide_Wide_String
, but nothing else; and destination in Ada usually requires destination and source to be of the same type. To convert a String
to Unbounded_String
, you need to call the function To_Unbounded_String
:
procedure anyname is
input_array : array(1..5) of Ada.Strings.Unbounded.Unbounded_String;
begin
input_array(1) := Ada.Strings.Unbounded.To_Unbounded_String ("12345");
end anyname;
You can shorten the name with a sentence use
; some other programmers might define their own rename function, perhaps even using the unary operator "+"
:
function "+" (Source : String) return Ada.Strings.Unbounded.Unbounded_String
renames Ada.Strings.Unbounded.To_Unbounded_String;
procedure anyname is
input_array : array(1..5) of Ada.Strings.Unbounded.Unbounded_String;
begin
input_array(1) := +"12345"; -- uses renaming "+" operator
end anyname;
Not everyone likes this style.
source to share
You can use the Ada.Strings.Unbounded
one illustrated here , or you can use the static dangling array illustrated here . The latter approach uses an array of aliases, each of which can have a different length.
type String_Access is access constant String;
String_5: aliased constant String := "12345";
String_6: aliased constant String := "123456";
String_7: aliased constant String := "1234567";
...
Input_Array: array (1..N) of
String_Access :=
(1 => String_5'Access,
2 => String_6'Access,
3 => String_7'Access,
-- etc. up to N
);
source to share