好的,这里是一个可能的解决方案:
main.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
procedure Main is
A : constant String := "John Johnson";
B : constant String := "son";
begin
if Tail (A, B'Length) = B then
Put_Line ("Yay!");
end if;
end Main;
输出
$ ./main
Yay!
更新(2)
另一个更新(感谢 @Brian Drummond 的评论;但该评论已经消失了),同样使用 Tail
。现在它与 @Zerte 的答案几乎完全相同,除了依赖于 Ada.Strings.Fixed
:
main.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Assertions; use Ada.Assertions;
procedure Main is
function Ends_With (Source, Pattern : String) return Boolean is
begin
return Source'Length >= Pattern'Length and then
Tail (Source, Pattern'Length) = Pattern;
end Ends_With;
begin
Assert (Ends_With ("John Johnson", "son") = True);
Assert (Ends_With ("hi", "longer than hi") = False);
Assert (Ends_With ("" , "" ) = True);
Assert (Ends_With (" " , "" ) = True);
Assert (Ends_With ("" , " " ) = False);
Assert (Ends_With (" " , " " ) = True);
Assert (Ends_With ("n ", "n ") = True);
Assert (Ends_With (" n", "n" ) = True);
Assert (Ends_With ("n" , " n") = False);
Assert (Ends_With (" n", " n") = True);
Put_Line ("All OK.");
end Main;
输出
$ ./main
All OK.
Ends_With
规范,我们无法正确回答这个问题。虽然Ada.Strings.Fixed.Tail
在预期情况下可以工作,但我们还需要知道在不太常见的情况下(A'Length < B'Length or B = ""
)Ends_With
应该做什么。 - Jeffrey R. Carter