Gustav Agrell
Gustav Agrell

Reputation: 175

Cutting a string at first space

I'm in the process of making my own package for an Ada main program. I read a string followed by an integer and another string and the problem is I need to cut the first string at sign of first space. I don't know how to do it and I've searched stack overflow only to find solutions in other languages.

My code right now in the package body is:

Get_Line(Item.String, Item.X1)

where X1 is an integer and String is the string. This works if you define the length in the type to match the exact length of your input but of course you want to be able to insert whatever you want and thus it doesn't work.

Can somebody point me in the right direction?

Thanks

Upvotes: 2

Views: 192

Answers (1)

Simon Wright
Simon Wright

Reputation: 25501

Why do you need to make a package for an Ada main program? Most compilers need them to be parameterless library-level procedures.

Anyway, this might give you some tips.

with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Agrell is
begin
   declare
      Line : constant String := Ada.Text_IO.Get_Line;

This is how to deal with reading a string of unknown length. You have to work out how to preserve it for future use (maybe use an Unbounded_String?)

      The_Integer : Integer;
   begin
      Looking_For_Space :
      for J in Line'Range loop
         if Line (J) = ' ' then

Everything from Line’First to J - 1 is the string you wanted.

            declare
               Dummy : Positive;
            begin
               Ada.Integer_Text_IO.Get (From => Line (J .. Line'Last),
                                        Item => The_Integer,
                                        Last => Dummy);
            end;

OK, now we have The Integer...

            ...
            exit Looking_For_Space;

... and we’re done with the first line.

         end if;
      end loop Looking_For_Space;
   end;
end Agrell;

Upvotes: 3

Related Questions