I'm trying to define an array of Strings in Ada to store Strings of variable size. The problem I have is that I must pre-define the size of my Strings which I don't know at compile time, and with the Unbounded_Strings the String_Split.Create wouldn't work, as it requires Standard.String.
Below is my code, where I need to be able to parse Strings of variable size, and not just the fixed length 4.
Thanks in advance.
type StrArray is array(1..7) of String(1..4);
function Split(Line : String;Sep : String) return StrArray is
Tokens : String_Split.Slice_Set;
Output : StrArray;
Count : Natural := 0;
begin
String_Split.Create(s => Tokens,
From => Line,
Separators => Sep,
Mode => String_Split.Single);
For I in 1 .. String_Split.Slice_Count (Tokens) loop
Count := Count + 1;
Output(Count) := String_Split.Slice(Tokens,I); -- Not sure how to convert Slice_Count to Integer either!
end loop;
return Output;
end Split;
The fact that
GNAT.String_Split
usesString
doesn’t mean that yourStrArray
has to. And you need to cater for input strings with varying numbers of tokens, so begin by declaringStrArray
as an unconstrained array type:Now
Split
begins like this:(we can’t declare
Output
yet, and we won’t needCount
; and I had to go to Google to find out thatString_Split
is a GNAT utility package).The first thing to do is to split the input line, so that we know how large
Output
needs to be (by the way, do you really wantSingle
?):Now we can declare
Output
using theSlice_Count
. Note the conversion toNatural
(notPositive
; if the input is an empty string, there will be no tokens, so the output will be an empty array, range1 .. 0
).Now fill
Output
with the tokens. AdaCore chose to implementSlice_Number
asnew Natural
, rather than as a subtype ofNatural
, which is why we need the conversion.... and return
Output
, within the declare block.To call
Split
, which is going to return aStrArray
whose length you don’t know beforehand, you can use the technique of constraint by initial value: