summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorDominik Picheta <dominikpicheta@googlemail.com>2017-10-22 23:11:13 +0100
committerGitHub <noreply@github.com>2017-10-22 23:11:13 +0100
commitecfbe4940b47ed608bd8f39243b7f032d68cc0cd (patch)
tree769278f74f8308edc2783a18f82741a15ee9fa5e /lib
parent7db5414d185974d57d2063b5821dbea05361baff (diff)
parent177a634992c378ec331c95e64c7f2ddd73154e77 (diff)
downloadNim-ecfbe4940b47ed608bd8f39243b7f032d68cc0cd.tar.gz
Merge pull request #6051 from couven92/alignLeft
Add left-aligning string proc to strutils
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/strutils.nim31
1 files changed, 29 insertions, 2 deletions
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim
index cc0f474f4..79e8210d4 100644
--- a/lib/pure/strutils.nim
+++ b/lib/pure/strutils.nim
@@ -1062,8 +1062,8 @@ proc align*(s: string, count: Natural, padding = ' '): string {.
   ##
   ## `padding` characters (by default spaces) are added before `s` resulting in
   ## 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
-  ## proc <#repeatChar>`_. Example:
+  ## returned unchanged. If you need to left align a string use the `alignLeft
+  ## proc <#alignLeft>`_. Example:
   ##
   ## .. code-block:: nim
   ##   assert align("abc", 4) == " abc"
@@ -1078,6 +1078,28 @@ proc align*(s: string, count: Natural, padding = ' '): string {.
   else:
     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[
   token: string, isSep: bool] =
   ## Tokenizes the string `s` into substrings.
@@ -2325,6 +2347,11 @@ when isMainModule:
   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
     inp = """ this is a long text --  muchlongerthan10chars and here
                it goes"""