std.string.translate using initializing twice?

simendsjo simen.endsjo at pandavre.com
Mon Aug 9 17:45:07 PDT 2010


translate does this:
     bool[256] deltab; // this would make all values of deltab false as 
bool.init == false, right?

     deltab[] = false;

Isn't this just initializing all values of deltab to false twice..?

And my "Is this more readable?"

Original:

string translate(string s, in string transtab, in string delchars)
     in
     {
     assert(transtab.length == 256);
     }
     body
     {
     char[] r;
     int count;
     bool[256] deltab;

     deltab[] = false;
     foreach (char c; delchars)
     {
         deltab[c] = true;
     }

     count = 0;
     foreach (char c; s)
     {
         if (!deltab[c])
         count++;
         //printf("s[%d] = '%c', count = %d\n", i, s[i], count);
     }

     r = new char[count];
     count = 0;
     foreach (char c; s)
     {
         if (!deltab[c])
         {
         r[count] = transtab[c];
         count++;
         }
     }

     return assumeUnique(r);
     }



"More readable?":


string translate(string s, in string transtab, in string delchars)
in
{
     assert(transtab.length == 256);
}
body
{
     // Mark characters to delete
     bool[256] deltab;
     foreach (char c; delchars)
         deltab[c] = true;

     // Count characters to translate
     int numToTranslate;
     foreach (char c; s)
     {
         if (!deltab[c])
             numToTranslate++;
     }

     char[] result = new char[numToTranslate];

     // Translate
     int translateIndex = 0;
     foreach (char c; s)
     {
         bool mustTranslate = !deltab[c];
         if (mustTranslate)
         {
             result[translateIndex] = transtab[c];
             translateIndex++;
         }
     }

     return assumeUnique(result);
}



More information about the Digitalmars-d-learn mailing list