Tal
Tal

Reputation: 235

String manipulation in ada

I am getting a path of directory in a string , like "C:\Users\Me\Desktop\Hello”, and I am trying to get the last directory, but without success.

I tried a lot of manipulation on the string but in the end of the day i stayed with nothing... i will be grateful to get some help. Thanks !

Here was my first idea :

Get_Line(Line, Len);
while (Line /="") loop
   FirstWord:=Index(Line(1..Len),"\")+1;
   declare
      NewLine :String := (Line(FirstWord .. Len));
   begin
      Line:=NewLine ; 
   end;
end loop;

I know its not working (I can’t assign NewLine to Line because there isn't a match between their lengths), and now I am stuck.

Upvotes: 0

Views: 1005

Answers (1)

Simon Wright
Simon Wright

Reputation: 25501

I’m assuming you want to manipulate directory (and file) names, rather than just any old string?

In which case you should look at the standard library packages Ada.Directories (ARM A.16) and Ada.Directories.Hierarchical_File_Names (ARM A.16.1):

with Ada.Directories;
with Ada.Text_IO; use Ada.Text_IO;
procedure Tal is
   Line : constant String := "C:\Users\Me\Desktop\Hello";
begin
   Put_Line ("Full_Name: "
               & Ada.Directories.Full_Name (Line));
   Put_Line ("Simple_Name: "
               & Ada.Directories.Simple_Name (Line));
   Put_Line ("Containing_Directory: "
               & Ada.Directories.Containing_Directory (Line));
   Put_Line ("Base_Name: "
               & Ada.Directories.Base_Name (Line));
end Tal;

On the other hand, if you’re trying to work out plain string manipulation, you could use something like

with Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
procedure Tal is

   function Get_Last_Word (From : String;
                           With_Separator : String)
                          return String is
      Separator_Position : constant Natural :=
        Ada.Strings.Fixed.Index (Source => From,
                                 Pattern => With_Separator,
                                 Going => Ada.Strings.Backward);
   begin
      --  This will fail if there are no separators in From
      return From (Separator_Position + 1 .. From'Last);   --'
   end Get_Last_Word;

   Line : constant String := "C:\Users\Me\Desktop\Hello";

   Last_Name : constant String := Get_Last_Word (Line, "\");

begin
   Put_Line (Last_Name);
end Tal;

As you can see, putting the logic in Get_Last_Word allows you to hoist Last_Name out of a declare block. But it will never be possible to overwrite a fixed string with a substring of itself (unless you’re prepared to deal with trailing blanks, that is): it’s much better never to try.

Upvotes: 8

Related Questions