Ada 95 Quality and Style Guide Chapter 8

Chapter 8: Reusability - TOC - 8.4 INDEPENDENCE

8.4.7 String Handling

guideline

  • Use the predefined packages for string handling.

  • example

    Writing code such as the following is no longer necessary in Ada 95:

    function Upper_Case (S : String) return String is
    
       subtype Lower_Case_Range is Character range 'a'..'z';
    
       Temp : String := S;
       Offset : constant := Character'Pos('A') - Character'Pos('a');
    
    begin
       for Index in Temp'Range loop
          if Temp(Index) in Lower_Case_Range then
             Temp(Index) := Character'Val (Character'Pos(Temp(Index)) + Offset);
          end if;
       end loop;
       return Temp;
    end Upper_Case;
    
    
    with Ada.Characters.Latin_1;
    function Trim (S : String) return String is
       Left_Index  : Positive := S'First;
       Right_Index : Positive := S'Last;
       Space : constant Character := Ada.Characters.Latin_1.Space;
    begin
       while (Left_Index < S'Last) and then (S(Left_Index) = Space) loop
          Left_Index := Positive'Succ(Left_Index);
       end loop;
    
       while (Right_Index > S'First) and then (S(Right_Index) = Space) loop
          Right_Index := Positive'Pred(Right_Index);
       end loop;
    
       return S(Left_Index..Right_Index);
    end Trim;
    
    
    

    Assuming a variable S of type String, the following expression:

    Upper_Case(Trim(S))
    
    

    can now be replaced by more portable and preexisting language-defined operations such as:

    with Ada.Characters.Handling;  use Ada.Characters.Handling;
    with Ada.Strings;              use Ada.Strings;
    with Ada.Strings.Fixed;        use Ada.Strings.Fixed;
    
    ...
    To_Upper (Trim (Source => S, Side => Both))
    

    rationale

    The predefined Ada language environment includes string handling packages to encourage portability. They support different categories of strings: fixed length, bounded length, and unbounded length. They also support subprograms for string construction, concatenation, copying, selection, ordering, searching, pattern matching, and string transformation. You no longer need to define your own string handling packages.


    < Previous Page Search Contents Index Next Page >
    1 2 3 4 5 6 7 8 9 10 11
    TOC TOC TOC TOC TOC TOC TOC TOC TOC TOC TOC
    Appendix References Bibliography