stringada

How do you check if string begins with or ends with another string in Ada?


There are canonical answers to this question for every popular language, even though that answer usually boils down to: "Use string.endsWith() from the standard library". For Ada, as far as I can find in the docs for the Fixed String package, there is no string.endswith function.

So, given two fixed strings A and B, how do you check if A ends with B?

declare
   A : constant String := "John Johnson";
   B : constant String := "son";
begin
   if A.Ends_With(B) then -- this doesn't compile
      Put_Line ("Yay!");
   end if;
end

My intent is to establish a standard answer for Ada. It would also be good to know how to check if a string starts with another string.


Solution

  • A slight simplification of Simon's answer:

    function Ends_With (Source, Pattern : String) return Boolean is
    begin
       return Pattern'Length <= Source'Length 
         and then Source (Source'Last - Pattern'Length + 1 .. Source'Last) = Pattern;
    end Ends_With;
    

    And similarly Starts_With would be:

    function Starts_With (Source, Pattern : String) return Boolean is
    begin
       return Pattern'Length <= Source'Length 
          and then Source (Source'First .. Source'First + Pattern'Length - 1) = Pattern;
    end Starts_With;