I have strings with different length, I want to fill them by symbol space, for example, to get string of the same length.
For instance, I have:
"1"
"3"
"12"
I need to get next result:
" 1"
" 3"
" 12"
Where all strings have length equals 3.
Additional question: Or maybe you know, how to initialize string of exact length that is filled one symbol. For example, String that has 5 space symbols.
" "
CodePudding user response:
You could use Scala API padTo to do what you need.
The only difference is that padTo
appends elements but you need it to prepend. It's easy to do it with double reverse
def padLeft(string: String, size: Int, char: Char) = {
string.reverse.padTo(size, char).reverse.mkString
}
Now, you can call it as following
padLeft("1", 3, ' ') .ensuring(_ == " 1")
padLeft("3", 3, ' ') .ensuring(_ == " 3")
padLeft("12", 3, ' ').ensuring(_ == " 12")
ensuring
is added to assert that the value equals to the expected one.
If you want to create a string filled with the same element, you can do it via collections API. For example this way
val string = LazyList.fill(5)(' ').mkString
string.ensuring(_ == " ")
CodePudding user response:
def leftPad(str: String, length: Int, char: Char): String = {
val diff = length - str.length
if (diff <= 0) str
else {
val sb = new StringBuilder
for (_ <- 0 until diff) sb.append(char)
sb.append(str).toString()
}
}