countUntil to print all the index of a given string.

Cym13 cpicard at openmailbox.org
Sun Feb 18 14:48:59 UTC 2018


On Sunday, 18 February 2018 at 11:55:37 UTC, Vino wrote:
> Hi All,
>
>   Request your help on printing the all index of an array 
> element , eg; the below code prints the index of the string 
> "Test2" as [1], but the string "Test2" is present 2 times at  
> index  1 and 4, so how do I print all the index of a given 
> string.
>
> import std.stdio;
> import std.container;
> import std.algorithm;
>
> void main () {
> auto a = Array!string("Test1", "Test2", "Test3", "Test1", 
> "Test2");
> writeln(SList!int(a[].countUntil("Test2"))[]);
> }
>
> Output
> [1]
>
> Expected
> [1, 4]
>
> From,
> Vino.B

countUntil is good when you want to avoid having to look at all 
your data, but in this case I don't think it's the best solution. 
You could do a loop storing each index and then restart your 
countUntil from there, but quite frankly it would be easier to 
just loop over the array at that point:

     ulong[] result;
     for (ulong index=0 ; index<a.length ; index++)
         if (a[index] == "Test2")
             result ~= index;
     writeln(result);

You could also use enumerate to make this a tad easier:

     import std.range: enumerate;

     ulong[] result;
     foreach (index, value ; a[].enumerate)
         if (a[index] == "Test2")
         result ~= index;
     writeln(result);

However, if you want a more streamlined, functionnal solution, 
you can go all the way and avoid all explicit loops and 
intermediate variables using fold:

     import std.range: enumerate;
     import std.algorithm: fold;

     a[]
      .enumerate
      .fold!((a, b) => b[1] == "Test2" ? a ~ b[0] : 
a)(cast(ulong[])[])
      .writeln;




More information about the Digitalmars-d-learn mailing list