By Alvin Alexander. Last updated: June 25, 2024
As a little Scala example, here’s a little Scala “string utilities” object that right- and left-justifies strings to a certain string width. Another way to say that is that the strings are left- and right-padded.
Also, the first function adds an ASCII underline to the string it’s given, so it expects a one-line string as input and returns a two-line string as output.
Here’s the source code for these Scala string utilities:
package com.alvinalexander.utils
object StringUtils:
def addAsciiUnderlineToString(s: String): String =
val underline = "-" * s.length
s"$s\n$underline"
/**
* Formats the given string so it is right-padded to a string
* that has the width specified. Ex: Given ("AAPL", 7) as
* input, it returns " AAPL".
* @param s The input string.
* @param width The desired width. Should be > s.length.
* @return A left-padded, right-justified string.
*/
def rightJustify(input: String, width: Int): String =
String.format(s"%${width}s", input)
/**
* Formats the given string so it is left-padded to a string
* that has the width specified. Ex: Given ("AAPL", 7) as
* input, it returns "AAPL ".
*
* @param s The input string.
* @param width The desired width. Should be > s.length.
* @return A right-padded, left-justified string.
*
* Note that the 'f' interpolator does not work in this case:
* f"$input%${width}s"
*/
def leftJustify(input: String, width: Int): String =
String.format(s"%-${width}s", input)
I’ll try to write more about these over time, but for now I’m just sharing that Scala source code.