본문 바로가기

빈 구멍 채우기

[Kotlin] 문자열 자리수 채우기 : padStart() padEnd()

kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/pad-start.html

 

padStart - Kotlin Programming Language

 

kotlinlang.org

kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/pad-end.html

 

padEnd - Kotlin Programming Language

 

kotlinlang.org

fun CharSequence.padStart(lenght: Int, padChar: Char = ' '): CharSequence

fun String.padStart(lenght: Int, padChar: Char = ' '): String

fun CharSequence.padEnd(lenght: Int, padChar: Char = ' '): CharSequence

fun String.padEnd(lenght: Int, padChar: Char = ' '): String

 

length: 원하는 문자열 길이

padChar : 문자열이 length보다 짧을 경우 빈 공간에 채워넣을 문자

 

val padWithSpace = "125".padStart(5)
println("'$padWithSpace'") // '  125'

val padWithChar = "a".padStart(5, '.')
println("'$padWithChar'") // '....a'

// string is returned as is, when its length is greater than the specified
val noPadding = "abcde".padStart(3)
println("'$noPadding'") // 'abcde'

val padWithSpace = "125".padEnd(5)
println("'$padWithSpace'") // '125  '

val padWithChar = "a".padEnd(5, '.')
println("'$padWithChar'") // 'a....'

// string is returned as is, when its length is greater than the specified
val noPadding = "abcde".padEnd(3)
println("'$noPadding'") // 'abcde'

결과

'  125'
'....a'
'abcde'
'125  '
'a....'
'abcde'