<div dir="ltr"><div>Is there a more idiomatic/elegant way to achieve the following, while remaining as efficient as possible? </div><div>Same question in the simpler case n==0?</div><div><br></div><div>using retro seems inefficient because of all the decodings</div>
<div><br></div><div>// returns the largest suffix of a that contains no more than n times c</div><div>string findBack(string a, char c, size_t n=0){</div><div> auto b=cast(immutable(ubyte)[])a;</div><div> auto val=cast(ubyte)c;</div>
<div> size_t counter=0;</div><div> for(ptrdiff_t i=cast(ptrdiff_t)b.length - 1; i>=0; i--){</div><div> if(b[i]==c){</div><div> if(counter>=n)</div><div> return cast(string)a[i+1..$];</div><div> counter++;</div>
<div> }</div><div> }</div><div> return a;</div><div>}</div><div><br></div><div>//unittest{</div><div>void test3(){</div><div> auto c='\n';</div><div> string a="abc1\nabc2\nabc3";</div><div> assert(a.findBack(c,0)=="abc3");</div>
<div> assert(a.findBack(c,1)=="abc2\nabc3");</div><div> assert(a.findBack(c,2)=="abc1\nabc2\nabc3");</div><div> assert(a.findBack(c,3)=="abc1\nabc2\nabc3");</div><div>}</div><div><br></div>
</div>