2016-12-14 48 views
1

在Ada中,我们可以给字符串比最初指定的字符少吗? 例如:Ada:字符串合法值?

Text : String(1..5); 
Text := "ada"; 

此编码是否正确?或者我们有义务给出一个5个字符的字符串?

谢谢。

+2

在这种情况下你需要一个5个字符的字符串(固定字符串)。还有其他选项,如Ada.Strings.Bounded和Ada.Strings.Unbounded,取决于您的需要 – egilhh

回答

6

使用类型String,您必须像使用Ada中的其他数组类型一样填充数组中的所有位置。

但也有一些技巧:

  • 初始化String(阵列),您声明它,你没有申报明确的范围:
declare 
    Text : constant String := "Ada"; 
begin 
    ... 
end; 
  • 选择String(阵列)中您想要放入什么的片段:
declare 
    subtype Five_Characters is String (1 .. 5); 
    Text : Five_Characters := (others => ' '); 
begin 
    Text (2 .. 4) := "Ada"; 
    ... 
end; 

使用Ada.Strings.Unbounded

declare 
    use Ada.Strings.Unbounded; 
    Text : Unbounded_String; 
begin 
    Text := To_Unbounded_String ("Ada"); 
    ... 
end; 
+1

正如@egilhh也提到的那样,您还可以根据需要使用Bounded_String。 [Ada Wikibook](https://en.wikibooks.org/wiki/Ada_Programming/Strings)给出了这些不同类型的完整概述。 –

1

代码是不正确的,你必须指定5个字符,例如

declare 
    Text : String(1..5); 
begin 
    Text := "ada "; 
end; 

或指定范围

declare 
    Text : String(1..5) := (others => ' '); -- Init to spaces 
begin 
    Text(1..3) := "ada";     -- Text now contains "ada " 
end; 

或使用可用的字符串处理软件包之一。