Biggest problems w/ D - strings
C. Dunn
cdunn2001 at gmail.com
Fri Aug 10 14:49:01 PDT 2007
Kirk McDonald Wrote:
> C. Dunn wrote:
> > 4) Not enough help for converting between D strings and C char*.
> > There must be conversion functions which work regardless of whether
> > the D string is dynamic or not, and regardless of whether the C char*
> > is null terminated. I'm not sure what the answer is, but this has
> > lead to a large number of runtime bugs for me as a novice.
> >
>
> The std.string module has the toStringz and toString functions.
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).
template min(T)
{
T min( T a, T b ) { if ( a < b ) return a; else return b; }
}
template max(T)
{
T max( T a, T b ) { if ( a < b ) return b; else return a; }
}
size_t strnlen(char* s, size_t maxlen){
for(size_t i=0; i<maxlen; ++i){
if (!s[i]) return i;
}
return maxlen;
}
int compare(ConstString lhs, ConstString rhs){
char* lptr = cast(char*)lhs;
char* rptr = cast(char*)rhs;
size_t len_lhs = strnlen(lptr, lhs.length);
size_t len_rhs = strnlen(rptr, rhs.length);
int comp = strncmp(lptr, rptr, min!(size_t)(len_lhs, len_rhs));
if (comp) return comp;
if (len_lhs < len_rhs) return -1;
else if (len_lhs > len_rhs) return 1;
else return 0;
}
More information about the Digitalmars-d
mailing list