술어와 일치하는 선행 및 후행 문자가 제거된 이 문자 시퀀스의 하위 시퀀스를 반환합니다.
public inline fun CharSequence.trim(predicate: (Char) -> Boolean): CharSequence {
var startIndex = 0
var endIndex = length - 1
var startFound = false
while (startIndex <= endIndex) {
val index = if (!startFound) startIndex else endIndex
val match = predicate(this[index])
if (!startFound) {
if (!match)
startFound = true
else
startIndex += 1
} else {
if (!match)
break
else
endIndex -= 1
}
}
return subSequence(startIndex, endIndex + 1)
}
val string = " Hello World "
println(string.trim()) // Hello World
val string2 = "!!!Hello World!!"
print(string2.trim('!')) // Hello World
술어와 일치하는 선행 문자가 제거된 문자열을 반환합니다.
public inline fun CharSequence.trimStart(predicate: (Char) -> Boolean): CharSequence {
for (index in this.indices)
if (!predicate(this[index]))
return subSequence(index, length)
return ""
}
val string = "!!!Hello World!!"
print(string.trimStart('!')) // Hello World!!
술어와 일치하는 후행 문자가 제거된 문자열을 반환합니다.
public inline fun CharSequence.trimEnd(predicate: (Char) -> Boolean): CharSequence {
for (index in this.indices.reversed())
if (!predicate(this[index]))
return subSequence(0, index + 1)
return ""
}
val string = "!!!Hello World!!"
print(string.trimStart('!')) // !!!Hello World
'코틀린 > [Mapping] 매핑 작업' 카테고리의 다른 글
[Kotlin][String] toInt (0) | 2024.09.03 |
---|---|
[Kotlin][Collection] toTypedArray (0) | 2024.08.30 |
[Kotlin][String] replaceRange (0) | 2024.08.27 |