Compare a string input to an Enumerated type

前端 未结 3 1120
北恋
北恋 2021-01-07 12:18

I am looking to do a comparison of a string to and enumeration. I have written a sample code of what I am attempting. Since a String and and Enumerated type are different, h

3条回答
  •  感动是毒
    2021-01-07 13:04

    Answering your actual question:

    Ada doesn't allow you to compare values of different types directly, but luckily there is a way to convert an enumerated type to a string, which always works.

    For any enumerated type T there exists a function:

    function T'Image (Item : in T) return String;
    

    which returns a string representation of the enumerated object passed to it.

    Using that, you can declare a function, which compares a string and an enumerated type:

    function "=" (Left  : in String;
                  Right : in Enumerated_Type) return Boolean is
    begin
       return Left = Enumerated_Type'Image (Right);
    end "=";
    

    If you want to do a case-insensitive comparison, you could map both strings to lower case before comparing them:

    function "=" (Left  : in String;
                  Right : in Enumerated_Type) return Boolean is
       use Ada.Characters.Handling;
    begin
       return To_Lower (Left) = To_Lower (Enumerated_Type'Image (Right));
    end "=";
    

提交回复
热议问题