Merge pull request #6051 from couven92/alignLeft

Add left-aligning string proc to strutils
This commit is contained in:
Dominik Picheta 2017-10-22 23:11:13 +01:00 • committed by GitHub
commit ecfbe4940b

View file

@ -1062,8 +1062,8 @@ proc align*(s: string, count: Natural, padding = ' '): string {.
## ##
## `padding` characters (by default spaces) are added before `s` resulting in ## `padding` characters (by default spaces) are added before `s` resulting in
## right alignment. If ``s.len >= count``, no spaces are added and `s` is ## right alignment. If ``s.len >= count``, no spaces are added and `s` is
## returned unchanged. If you need to left align a string use the `repeatChar ## returned unchanged. If you need to left align a string use the `alignLeft
## proc <#repeatChar>`_. Example: ## proc <#alignLeft>`_. Example:
## ##
## .. code-block:: nim ## .. code-block:: nim
## assert align("abc", 4) == " abc" ## assert align("abc", 4) == " abc"
@ -1078,6 +1078,28 @@ proc align*(s: string, count: Natural, padding = ' '): string {.
else: else:
result = s result = s
proc alignLeft*(s: string, count: Natural, padding = ' '): string {.noSideEffect.} =
## Left-Aligns a string `s` with `padding`, so that it is of length `count`.
##
## `padding` characters (by default spaces) are added after `s` resulting in
## left alignment. If ``s.len >= count``, no spaces are added and `s` is
## returned unchanged. If you need to right align a string use the `align
## proc <#align>`_. Example:
##
## .. code-block:: nim
## assert alignLeft("abc", 4) == "abc "
## assert alignLeft("a", 0) == "a"
## assert alignLeft("1232", 6) == "1232 "
## assert alignLeft("1232", 6, '#') == "1232##"
if s.len < count:
result = newString(count)
if s.len > 0:
result[0 .. (s.len - 1)] = s
for i in s.len ..< count:
result[i] = padding
else:
result = s
iterator tokenize*(s: string, seps: set[char] = Whitespace): tuple[ iterator tokenize*(s: string, seps: set[char] = Whitespace): tuple[
token: string, isSep: bool] = token: string, isSep: bool] =
## Tokenizes the string `s` into substrings. ## Tokenizes the string `s` into substrings.
@ -2325,6 +2347,11 @@ when isMainModule:
doAssert align("1232", 6) == " 1232" doAssert align("1232", 6) == " 1232"
doAssert align("1232", 6, '#') == "##1232" doAssert align("1232", 6, '#') == "##1232"
doAssert alignLeft("abc", 4) == "abc "
doAssert alignLeft("a", 0) == "a"
doAssert alignLeft("1232", 6) == "1232 "
doAssert alignLeft("1232", 6, '#') == "1232##"
let let
inp = """ this is a long text -- muchlongerthan10chars and here inp = """ this is a long text -- muchlongerthan10chars and here
it goes""" it goes"""