http://d.puremagic.com/issues/show_bug.cgi?id=7716
Summary: Add an indexed overload to countUntil Product: D Version: D2 Platform: All OS/Version: All Status: NEW Severity: enhancement Priority: P2 Component: Phobos AssignedTo: nob...@puremagic.com ReportedBy: andrej.mitrov...@gmail.com --- Comment #0 from Andrej Mitrovic <andrej.mitrov...@gmail.com> 2012-03-15 09:55:27 PDT --- Sometimes I want to find the index of a substring, but not necessarily the index of the first occurence. E.g. in the string "foo x foo y" I want to get the index of the second foo. Here's a simple implementation based on the existing countUntil: import std.algorithm : startsWith; import std.array; import std.traits; sizediff_t countUntil(alias pred = "a == b", R, N)(R haystack, N needle, size_t index) if (is(typeof(startsWith!pred(haystack, needle)))) { size_t count; static if (isNarrowString!R) { // Narrow strings are handled a bit differently auto length = haystack.length; for (; !haystack.empty; haystack.popFront()) { if (startsWith!pred(haystack, needle)) { if (count == index) return length - haystack.length; else count++; } } } else { typeof(return) result; for (; !haystack.empty; ++result, haystack.popFront()) { if (startsWith!pred(haystack, needle)) { if (count == index) return result; else count++; } } } return -1; } void main() { string s = "foo x foo y"; auto idx1 = s.countUntil("foo", 0); auto idx2 = s.countUntil("foo", 1); auto idx3 = s.countUntil("foo", 2); assert(idx1 == 0); assert(idx2 == 6); assert(idx3 == -1); } Equivalent functionality could be added to std.string.indexOf to allow case-unsensitive searches. -- Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: -------