RosettaCodeData/Task/Multisplit/D/multisplit.d

39 lines
865 B
D
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
import std.stdio, std.array, std.algorithm;
2015-02-20 00:35:01 -05:00
string[] multiSplit(in string s, in string[] divisors) pure nothrow {
2013-04-10 21:29:02 -07:00
string[] result;
2015-02-20 00:35:01 -05:00
auto rest = s.idup;
2013-04-10 21:29:02 -07:00
while (true) {
bool done = true;
string delim;
{
string best;
2015-02-20 00:35:01 -05:00
foreach (const div; divisors) {
2013-10-27 22:24:23 +00:00
const maybe = rest.find(div);
2013-04-10 21:29:02 -07:00
if (maybe.length > best.length) {
best = maybe;
delim = div;
done = false;
}
}
}
result.length++;
if (done) {
2013-10-27 22:24:23 +00:00
result.back = rest.idup;
2013-04-10 21:29:02 -07:00
return result;
} else {
2013-10-27 22:24:23 +00:00
const t = rest.findSplit(delim);
result.back = t[0].idup;
2013-04-10 21:29:02 -07:00
rest = t[2];
}
}
}
void main() {
2013-10-27 22:24:23 +00:00
"a!===b=!=c"
.multiSplit(["==", "!=", "="])
.join(" {} ")
.writeln;
2013-04-10 21:29:02 -07:00
}