overlapping as a parameter for count instead

This commit is contained in:
def 2014-07-28 16:48:07 +02:00
commit c78b1070a8

View file

@ -803,15 +803,19 @@ proc rfind*(s, sub: string, start: int = -1): int {.noSideEffect.} =
if result != -1: return if result != -1: return
return -1 return -1
proc count*(s: string, sub: string): int {.noSideEffect, proc count*(s: string, sub: string, overlapping: bool = false): int {.noSideEffect,
rtl, extern: "nsuCountString".} = rtl, extern: "nsuCountString".} =
## Count the occurences of a substring `sub` in the string `s`. Overlapping ## Count the occurences of a substring `sub` in the string `s`.
## occurences of `sub` do not count. ## Overlapping occurences of `sub` only count when `overlapping`
## is set to true.
var i = 0 var i = 0
while true: while true:
i = s.find(sub, i) i = s.find(sub, i)
if i < 0: if i < 0:
break break
if overlapping:
inc i
else:
i += sub.len i += sub.len
inc result inc result
@ -829,18 +833,6 @@ proc count*(s: string, subs: set[char]): int {.noSideEffect,
if c in subs: if c in subs:
inc result inc result
proc countOverlapping*(s: string, sub: string): int {.noSideEffect,
rtl, extern: "nsuCountOverlapping".} =
## Count the occurences of a substring `sub` in the string `s`. Overlapping
## occurences of `sub` do count.
var i = 0
while true:
i = s.find(sub, i)
if i < 0:
break
inc i
inc result
proc quoteIfContainsWhite*(s: string): string {.deprecated.} = proc quoteIfContainsWhite*(s: string): string {.deprecated.} =
## Returns ``'"' & s & '"'`` if `s` contains a space and does not ## Returns ``'"' & s & '"'`` if `s` contains a space and does not
## start with a quote, else returns `s`. ## start with a quote, else returns `s`.
@ -1394,6 +1386,6 @@ when isMainModule:
doAssert parseEnum("invalid enum value", enC) == enC doAssert parseEnum("invalid enum value", enC) == enC
doAssert count("foofoofoo", "foofoo") == 1 doAssert count("foofoofoo", "foofoo") == 1
doAssert countOverlapping("foofoofoo", "foofoo") == 2 doAssert count("foofoofoo", "foofoo", overlapping = true) == 2
doAssert count("foofoofoo", 'f') == 3 doAssert count("foofoofoo", 'f') == 3
doAssert count("foofoofoobar", {'f','b'}) == 4 doAssert count("foofoofoobar", {'f','b'}) == 4