在 Ada 中初始化固定长度字符串的最佳方法是什么?

问题描述 投票:0回答:2

我想在 Ada 中初始化一个固定长度的

String
或多或少如下:

S : String (1..256) := ("Hello", others => Character'Val (0));

我在尝试编译时遇到错误。 有没有办法实现类似上面的效果?

string ada bounded-types
2个回答
6
投票

您的代码无法编译的原因是 String 是一个字符数组,因此等价物是

s : String(1..256) := (1 => 'H',
                       2 => 'e',
                       3 => 'l',
                       4 => 'l',
                       5 => 'o',
                       others => Character'Val(0));

这显然远非理想。

另一种方法是使用 [Ada.Strings.Fixed][1] 中的 Move 过程。

Move(Target => s,
     Source => "Hello",
     Pad => Character'Val(0));

但这不能在声明中完成。

最后,编译完成:

s : String(1..256) := "Hello" & (6..256 => Character'Val(0));

但我觉得不太清楚 [1]:http://www.ada-auth.org/standards/rm12_w_tc1/html/RM-A-4-3.html


1
投票

我通常会做类似的事情

Hello : constant String := "Hello";

Desired_Length : constant := 256;

S : String := Hello & (1 .. Desired_Length - Hello'Length => Character'Val (0) );

(Hello'Length + 1 .. Desired_Length => ...);
© www.soinside.com 2019 - 2024. All rights reserved.