Re: Is there a d analog of strncmp?

2016-08-23 Thread cy via Digitalmars-d-learn

import std.algorithm.searching: startsWith, commonPrefix;
if(s1.startsWith(s2)) {...}
string prefix = commonPrefix(s1,s2);


Re: Is there a d analog of strncmp?

2016-08-21 Thread dan via Digitalmars-d-learn

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!




Re: Is there a d analog of strncmp?

2016-08-21 Thread Jonathan M Davis via Digitalmars-d-learn
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



Re: Is there a d analog of strncmp?

2016-08-21 Thread Adam D. Ruppe via Digitalmars-d-learn

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);
}


Is there a d analog of strncmp?

2016-08-21 Thread dan via Digitalmars-d-learn
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!