findBack: find a needle in a haystack from the back

Timothee Cour via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 9 00:58:17 PDT 2014


Is there a more idiomatic/elegant way to achieve the following, while
remaining as efficient as possible?
Same question in the simpler case n==0?

using retro seems inefficient because of all the decodings

// returns the largest suffix of a that contains no more than n times c
string findBack(string a, char c, size_t n=0){
  auto b=cast(immutable(ubyte)[])a;
  auto val=cast(ubyte)c;
  size_t counter=0;
  for(ptrdiff_t i=cast(ptrdiff_t)b.length - 1; i>=0; i--){
    if(b[i]==c){
      if(counter>=n)
        return cast(string)a[i+1..$];
      counter++;
    }
  }
  return a;
}

//unittest{
void test3(){
  auto c='\n';
  string a="abc1\nabc2\nabc3";
  assert(a.findBack(c,0)=="abc3");
  assert(a.findBack(c,1)=="abc2\nabc3");
  assert(a.findBack(c,2)=="abc1\nabc2\nabc3");
  assert(a.findBack(c,3)=="abc1\nabc2\nabc3");
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20140609/f75ac22a/attachment.html>


More information about the Digitalmars-d-learn mailing list