diff options
author | Bo Lingen <lingenbw@gmail.com> | 2017-10-28 03:47:23 -0500 |
---|---|---|
committer | Andreas Rumpf <rumpf_a@web.de> | 2017-10-28 10:47:23 +0200 |
commit | e13513546981167e4d1ee38993b2589e14531fb9 (patch) | |
tree | 2e8fe3fe3a6c2a7ab96164bf5331ce99cd8e63b5 /lib | |
parent | 616db85c615d9cf00a1c3b85e59cf6401fed915b (diff) | |
download | Nim-e13513546981167e4d1ee38993b2589e14531fb9.tar.gz |
add `strutils.removePrefix` proc (#6473)
Diffstat (limited to 'lib')
-rw-r--r-- | lib/pure/strutils.nim | 40 |
1 files changed, 38 insertions, 2 deletions
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index 9400e5c02..1556f7c68 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -2345,8 +2345,7 @@ proc removeSuffix*(s: var string, chars: set[char] = Newlines) {. proc removeSuffix*(s: var string, c: char) {. rtl, extern: "nsuRemoveSuffixChar".} = - ## Removes a single character (in-place) from a string. - ## + ## Removes a single character (in-place) from the end of a string. ## .. code-block:: nim ## var ## table = "users" @@ -2368,6 +2367,43 @@ proc removeSuffix*(s: var string, suffix: string) {. newLen -= len(suffix) s.setLen(newLen) +proc removePrefix*(s: var string, chars: set[char] = Newlines) {. + rtl, extern: "nsuRemovePrefixCharSet".} = + ## Removes all characters from `chars` from the start of the string `s` + ## (in-place). + ## .. code-block:: nim + ## var userInput = "\r\n*~Hello World!" + ## userInput.removePrefix + ## doAssert userInput == "*~Hello World!" + ## userInput.removePrefix({'~', '*'}) + ## doAssert userInput == "Hello World!" + ## + ## var otherInput = "?!?Hello!?!" + ## otherInput.removePrefix({'!', '?'}) + ## doAssert otherInput == "Hello!?!" + var start = 0 + while start < s.len and s[start] in chars: start += 1 + if start > 0: s.delete(0, start - 1) + +proc removePrefix*(s: var string, c: char) {. + rtl, extern: "nsuRemovePrefixChar".} = + ## Removes a single character (in-place) from the start of a string. + ## .. code-block:: nim + ## var ident = "pControl" + ## ident.removePrefix('p') + ## doAssert ident == "Control" + removePrefix(s, chars = {c}) + +proc removePrefix*(s: var string, prefix: string) {. + rtl, extern: "nsuRemovePrefixString".} = + ## Remove the first matching prefix (in-place) from a string. + ## .. code-block:: nim + ## var answers = "yesyes" + ## answers.removePrefix("yes") + ## doAssert answers == "yes" + if s.startsWith(prefix): + s.delete(0, prefix.len - 1) + when isMainModule: doAssert align("abc", 4) == " abc" doAssert align("a", 0) == "a" |