String Arrays in Ada

百般思念 提交于 2020-01-14 19:07:29

问题


I have a program in Ada95, in which I have to create an array of strings. This array can contain strings of variable length.

Example: I have declared the array in which all the indexes can store strings of size 50. When I assign a smaller string to the above array, I get "Constraint Error".

Code:

procedure anyname is
    input_array : array(1..5) of String(1..50);
begin
    input_array(1):="12345";
end anyname;

I have tried to create the array of Unbounded_Strings. But that doesn't work either. Can anyone tell me how to store this "12345" in the above string array?


回答1:


If you use Unbounded_String, you cannot assign a string literal to it directly. String literals can have type String, Wide_String, or Wide_Wide_String, but nothing else; and assignment in Ada usually requires that the destination and source be the same type. To convert a String to an Unbounded_String, you need to call the To_Unbounded_String function:

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 by using a use clause; some other programmers might define their own renaming function, possibly 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.




回答2:


You can use Ada.Strings.Unbounded, illustrated here, or you can use a static ragged array, illustrated here. The latter approach uses an array of aliased components, each of which may 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
      );


来源:https://stackoverflow.com/questions/26684909/string-arrays-in-ada

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!