diff options
author | Andreas Rumpf <rumpf_a@web.de> | 2014-09-05 08:36:07 +0200 |
---|---|---|
committer | Andreas Rumpf <rumpf_a@web.de> | 2014-09-05 08:36:07 +0200 |
commit | 43f78d2c4a3d8dccec5c9e8a156e95f00f307efd (patch) | |
tree | 65ac8afe22aef784fb9773f89b46db54d0b46d10 | |
parent | 6abd67360652430988e297f583cd1296e0d2c1ab (diff) | |
parent | c78b1070a8dec61ae6aa660fe724bf9fb67fb6a9 (diff) | |
download | Nim-43f78d2c4a3d8dccec5c9e8a156e95f00f307efd.tar.gz |
Merge pull request #1404 from def-/strutils-count
Add count procedures to strutils
-rw-r--r-- | lib/pure/strutils.nim | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index 6f8924d83..1d17de233 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -803,6 +803,36 @@ proc rfind*(s, sub: string, start: int = -1): int {.noSideEffect.} = if result != -1: return return -1 +proc count*(s: string, sub: string, overlapping: bool = false): int {.noSideEffect, + rtl, extern: "nsuCountString".} = + ## Count the occurences of a substring `sub` in the string `s`. + ## Overlapping occurences of `sub` only count when `overlapping` + ## is set to true. + var i = 0 + while true: + i = s.find(sub, i) + if i < 0: + break + if overlapping: + inc i + else: + i += sub.len + inc result + +proc count*(s: string, sub: char): int {.noSideEffect, + rtl, extern: "nsuCountChar".} = + ## Count the occurences of the character `sub` in the string `s`. + for c in s: + if c == sub: + inc result + +proc count*(s: string, subs: set[char]): int {.noSideEffect, + rtl, extern: "nsuCountCharSet".} = + ## Count the occurences of the group of character `subs` in the string `s`. + for c in s: + if c in subs: + inc result + proc quoteIfContainsWhite*(s: string): string {.deprecated.} = ## Returns ``'"' & s & '"'`` if `s` contains a space and does not ## start with a quote, else returns `s`. @@ -1354,3 +1384,8 @@ when isMainModule: doAssert parseEnum[TMyEnum]("enu_D") == enuD doAssert parseEnum("invalid enum value", enC) == enC + + doAssert count("foofoofoo", "foofoo") == 1 + doAssert count("foofoofoo", "foofoo", overlapping = true) == 2 + doAssert count("foofoofoo", 'f') == 3 + doAssert count("foofoofoobar", {'f','b'}) == 4 |