with Ada.Characters.Latin_1;
with Ada.Strings.Unbounded;
with Ada.Text_IO; 
with Ada.Text_IO.Unbounded_IO;
with GNAT.String_Split;
 
procedure Foobar is
   use Ada.Characters;
   use Ada.Strings.Unbounded;
   use Ada.Text_IO;
   use Ada.Text_IO.Unbounded_IO;
   use GNAT;
 
   Data : constant String := 
            "This becomes a " & Latin_1.HT & " bunch of     substrings";
   --  The input data, normally would be read from some external source or 
   --  whatever. Latin_1.HT is a horizontal tab.
 
   Subs : String_Split.Slice_Set;
   --  Subs is populated by the actual substrings.
 
   Seps : constant String := " " & Latin_1.HT;  
   --  just arbitrary simple set of whitespace.
 
   Sub : Unbounded_String;
   --  Object to a slice.
begin
   Put_Line ("Splitting '" & Data & "' at whitespace.");
   --  Introduce our job
 
   String_Split.Create (S          => Subs,
                        From       => Data,
                        Separators => Seps,
                        Mode       => String_Split.Multiple);
   --  Create the split, using Multiple mode to treat strings of multiple
   --  whitespace characters as a single separator.
   --  This populates the Subs object.
 
   Put_Line 
     ("Got" & 
      String_Split.Slice_Number'Image (String_Split.Slice_Count (Subs)) &
      " substrings:");
   --  Report results, starting with the count of substrings created
 
   for I in 1 .. String_Split.Slice_Count (Subs) loop
      --  Loop though the substrings
 
      --  Note that we've avoided the block from the first example. This is
      --  possible because our Sub variable is now an Unbounded_String, which
      --  does not have to be declared with an initial length.
 
      Sub := To_Unbounded_String (String_Split.Slice (Subs, I));
      --  Pull the next substring out into an Unbounded_String object for 
      --  easy handling. String_Split.Slice return a String, which we convert
      --  to an Unbounded_String using the aptly named To_Unbounded_String
      --  function.
 
      Put (String_Split.Slice_Number'Image (I));
      Put (" -> "); 
      Put (Sub); 
      Put (" (length" & Positive'Image (Length (Sub)) & ")");
      New_Line;
   end loop;
end Foobar;

Go back


Navigation