www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is there a d analog of strncmp?

reply dan <dan.hitt gmail.com> writes:
In c, there's this very nice function strncmp(s1,s2,count) which 
compares two c strings, using at most count characters.  count 
can be less than, more than, or equal to either or both of the 
lengths of the two strings.  It can be used to see if two 
c-strings have the same prefix of some length.

Now, strncmp indeed seems to be packaged up in core.stdc.string, 
but i would like to use some something like it on 2 d strings 
(which, as i understand it, need not be zero-terminated).

I suppose it would be possible to do some conversion with 
toStringz() or something and then invoke the strncmp(), but that 
seems very wordy and also it's not clear that it would handle all 
pairs of d strings (e.g., what if there were some 0's in the 
first count characters?).

So i would like to call a d function which works on d strings, 
but don't want to write my own if one already exists.  (At the 
very least, i'd have to get a much sharper understanding of d 
strings, whether internal 0's can occur, etc.  And i would not 
want to do egregious string allocation.)

TIA for any info!
Aug 21 2016
next sibling parent reply Adam D. Ruppe <destructionator gmail.com> writes:
int strncmp(string a, string b, int n) {
	if(a.length > n)
		a = a[0 .. n];
	if(b.length > n)
		b = b[0 .. n];
	import std.algorithm.comparison : cmp;
	return cmp(a, b);
}
Aug 21 2016
parent reply Jonathan M Davis via Digitalmars-d-learn writes:
On Monday, August 22, 2016 00:14:31 Adam D. Ruppe via Digitalmars-d-learn 
wrote:
 int strncmp(string a, string b, int n) {
   if(a.length > n)
       a = a[0 .. n];
   if(b.length > n)
       b = b[0 .. n];
   import std.algorithm.comparison : cmp;
   return cmp(a, b);
 }
Aside from the imports, it can be turned into a one-liner if you use take: return cmp(take(a, n), take(b, n)); - Jonathan M Davis
Aug 21 2016
parent dan <dan.hitt gmail.com> writes:
On Monday, 22 August 2016 at 01:45:02 UTC, Jonathan M Davis wrote:
 On Monday, August 22, 2016 00:14:31 Adam D. Ruppe via 
 Digitalmars-d-learn wrote:
 int strncmp(string a, string b, int n) {
   if(a.length > n)
       a = a[0 .. n];
   if(b.length > n)
       b = b[0 .. n];
   import std.algorithm.comparison : cmp;
   return cmp(a, b);
 }
Aside from the imports, it can be turned into a one-liner if you use take: return cmp(take(a, n), take(b, n)); - Jonathan M Davis
Thanks Adam and Jonathan for your solutions. For reference, one of the imports Jonathan is referring to is import std.range; I did not know about take. Well, i also did not know about cmp. So my code is probably not very idiomatic. But i do appreciate all of you d-learn people!
Aug 21 2016
prev sibling parent cy <dlang verge.info.tm> writes:
import std.algorithm.searching: startsWith, commonPrefix;
if(s1.startsWith(s2)) {...}
string prefix = commonPrefix(s1,s2);
Aug 23 2016