Ada中的字符串数组 [英] String Arrays in Ada
问题描述
我在Ada95中有一个程序,其中必须创建一个字符串数组。该数组可以包含长度可变的字符串。
I have a program in Ada95, in which I have to create an array of strings. This array can contain strings of variable length.
示例:
我声明了一个数组,其中所有索引都可以存储大小为50的字符串。当我分配时上面的数组中的一个较小的字符串,我得到约束错误。
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".
代码:
procedure anyname is
input_array : array(1..5) of String(1..50);
begin
input_array(1):="12345";
end anyname;
我尝试创建Unbounded_Strings数组。但这也不起作用。谁能告诉我如何在上面的字符串数组中存储这个 12345吗?
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?
推荐答案
如果您使用 Unbounded_String
,您不能直接为它分配字符串文字。字符串文字可以具有 String
, Wide_String
或 Wide_Wide_String
类型, 但没有别的;并且Ada中的分配通常要求目标和源的类型相同。要将 String
转换为 Unbounded_String
,需要调用 To_Unbounded_String
函数:
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.
这篇关于Ada中的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!