Created
June 26, 2018 08:29
-
-
Save JoolsF/ef7892bd6c691acc6791292d5d9bc86e to your computer and use it in GitHub Desktop.
String pad example 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| object StringUtils { | |
| implicit class RichString(s: String) { | |
| /** | |
| * Take a string and int representing the desired string length. | |
| * Front pads the string with a char up to the desired length | |
| * | |
| * @param l length of string | |
| * @param c char to pad | |
| * @return | |
| */ | |
| def leftPad(l: Int, c: Char = '0'): String = | |
| if (l < s.length) { | |
| s | |
| } else { | |
| val zeroes: String = (1 to l).map(_ => c).mkString | |
| (zeroes + s).substring(s.length()) | |
| } | |
| } | |
| } | |
| import StringUtils._ | |
| "foo".leftPad(10, 'x') //res0: String = xxxxxxxfoo | |
| "foo".leftPad(2) //res1: String = foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment