oartart
oartart

Reputation: 126

Ada.Strings.Fixed.Index unexpected results in loop

I have a simple procedure which splits a string and then searches substrings inside them. I'm getting weird results but I dont quite grasp why. I suspect it might be related to Ada evaluation strategy or something like that.

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with GNAT.String_Split; use GNAT;

procedure Split_Test is
    Subs : String_Split.Slice_Set;
begin
    String_Split.Create (Subs, "abcdSEPabcd", "SEP", String_Split.Multiple);

    for Substring of Subs loop
        declare
            Idx : Integer := Index(Substring, "abc");
        begin
            Put_Line("index of abc is" & Integer'Image(Idx) & " within string " & Substring);
        end;
    end loop;
end;

When I run it, i get:

index of abc is 1 within string abcd
index of abc is 8 within string abcd

Clearly index of abc should be 1 on both iterations. What's the issue here?

Upvotes: 1

Views: 197

Answers (1)

Jere
Jere

Reputation: 3641

Ada allows for strings to be indexed starting at any valid Positive value. What it appears is that the GNAT split function (Create) is simply ensuring that the substrings use the same indexes as their data had in the original combined string. Which is useful for finding the original index of the value you are looking for.

If you want the answer to always be 1 for the first index, you'll need to do the legwork of subtracting Substring'First and adding 1 to the index, but honestly there shouldn't be any need for that. Just make sure your code handling the substring always uses operations relative to Substring'First and it won't matter what the first index is.

Upvotes: 3

Related Questions