Re: Is there a d analog of strncmp?
import std.algorithm.searching: startsWith, commonPrefix; if(s1.startsWith(s2)) {...} string prefix = commonPrefix(s1,s2);
Re: Is there a d analog of strncmp?
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?
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?
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); }