Skip to content

Instantly share code, notes, and snippets.

@JoolsF
Created June 26, 2018 08:29
Show Gist options
  • Select an option

  • Save JoolsF/ef7892bd6c691acc6791292d5d9bc86e to your computer and use it in GitHub Desktop.

Select an option

Save JoolsF/ef7892bd6c691acc6791292d5d9bc86e to your computer and use it in GitHub Desktop.
String pad example 1
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