Biggest problems w/ D - strings

Derek Parnell derek at psych.ward
Sat Aug 11 03:07:51 PDT 2007


On Fri, 10 Aug 2007 17:49:01 -0400, C. Dunn wrote:

> 
> I have a field of n chars stored on disk.  It holds a
> null-terminated string, padded with zeroes.
> It is amazingly difficult to compare such a char[n]
> with some other char[] (which, by the dictates of D,
> may or may not be null-terminated).

You could try this simpler method ...

import std.string;
// Return a slice of the leftmost portion of 'x'
// up to but not including the first 'c'
string lefts(string x, char c)
{
    int p;
    p = std.string.find(x,c);
    if (p < 0)
        p = x.length;
    return x[0..p];
}

int compare(string lhs, string rhs, char d = '\0')
{
    return std.string.cmp( lefts(lhs,d), lefts(rhs,d) );
}

and use it like ...

   char[32] NameA;
   char[56] NameB;
   NameA[] = ' '; 
   NameB[] = ' ';

   NameA[0..5] = "derek";
   NameB[0..7] = "parnell";
   result = compare(NameA, NameB);

-- 
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell



More information about the Digitalmars-d mailing list