Ada中的编码:字符串(IV)不受限制

2021-02-19 17:04:51

如前所述,Ada中的字符串可能很棘手。普通字符串的长度是固定的,而Ada对此非常严格。考虑一段这样的代码:

与ada.Text_IO;使用Ada.Text_IO;和ada.strings.unbounded;使用ada.strings.unbounded;程序ustr2strfail是功能tub(Source:String)返回unbounded_string重命名ada.strings.unbounded.to_unbounded_string;词典类型是unbounded_string的array(1..10);单词:词典:=(tub(" gum"),tub(" sin"),tub(" cry"),tub(" lug&# 34;),浴缸(" star),浴缸(" fault"),浴缸(" sleeper"),浴缸(" a" ),tub(" vader"),tub(" nordic")); aword:string(1..10);开始aword:= to_string(words(7)); put(aword); end ustr2strfail;

这意味着尽管使用函数to_string()将无界字符串转换为字符串,但仅当无界字符串的长度等于字符串aword的长度时,该字符串才有效。因此,在上面的代码中,word的长度为10,并且尝试为它分配无限制的字符串“ sleeper”时,它将失败。如果在轨枕后面加了3个空格,它将起作用。如何解决这个问题?做到这一点,填入文字。这是执行此操作的子例程:

与ada.Text_IO;使用Ada.Text_IO;和ada.strings.unbounded;与ada.strings.unbounded.Text_IO一起使用ada.strings.unbounded;使用ada.strings.unbounded.Text_IO;固定ada.strings.fixed;使用ada.strings.fixed;程序ustr2str是子类型string10是string(1..10); R:字符串10;函数tub(Source:String)返回unbounded_string重命名ada.strings.unbounded.to_unbounded_string;词典类型是unbounded_string的array(1..10);单词:词典:=(tub(" gum"),tub(" sin"),tub(" cry"),tub(" lug&# 34;),浴缸(" star),浴缸(" fault"),浴缸(" sleeper"),浴缸(" a" ),tub(" vader"),tub(" nordic"));函数padString(V:unbounded_string)返回string10是temp:常量字符串:= to_string(V); res:字符串10;开始ada.strings.fixed.move(temp,res,drop => ada.strings.right);返回资源; end padString;开始R:= padString(words(7)); put(R); end ustr2str;

它使用ada.strings.fixed包中的过程move()。它具有以下基本形式:

过程Move(源:in字符串; Target:out字符串; Drop:截断:=错误; Justify:对齐:=左; Pad:字符:=空格);

过程move()将字符从源复制到目标。如果Source与Target的长度相同,则效果是将Source分配给Target。如果“源”比“目标”短,则将“对齐”用于将“源”放入目标(默认值=“左”)。填充指定填充,默认为空格。如果源比目标长,则使用丢弃。