Howto Re-Index an String in Ada?

75 views Asked by At

I having the problem to Re-Index an Sliced string,

    procedure String_Test is

      mystr:String:="Hello World";
      str:String:=mystr(6 .. 11);
      str_re_indexed:String:=Trim(Str, Left); -- it works but whitespace is removed

   begin
      
      for K in str_re_indexed'First .. str_re_indexed'Last loop
         Put_Line(Integer'Image(K));
      end loop;

   end String_Test;

After Re-Indexing the string should be (1 ..6)
Is there any predefined Ada function to do that ?

3

There are 3 answers

0
Maxim Reznik On BEST ANSWER

you can define a string subtype for this:

subtype String_1_6 is String (1 .. 6);
Result : String := String_1_6 (My_Str);
0
Jeffrey R. Carter On

To generalize Reznik's answer, your subtype would have bounds

1 .. My_Str'Length

Often you can combine the subtype and the object:

Result : String (1 .. My_Str'Length) := My_Str;
0
Jim Rogers On

Ada automatically slides slices to new index values upon assignment of a slice to another string.

with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   mystr          : String := "Hello World";
   str_re_indexed : String (1 .. 6);

begin
   str_re_indexed := mystr (6 .. 11);
   Put_Line
     ("str_re_indexed index range:" & Positive'Image (str_re_indexed'First) &
      " .." & Positive'Image (str_re_indexed'Last));
   Put_Line ("str_re_indexed : " & str_re_indexed);
end Main;