22.09.05 TIL (알파벳 대소문자 변환, 문자열 처음, 끝 떼어내기)

ddanglehee·2022년 9월 5일
0

TIL

목록 보기
2/9

📌 Kotlin 문법

String 알파벳 대문자 ↔️ 소문자 변환

  • 모두 원본을 파괴하지는 않는다.

📍 uppercase()

String에 있는 소문자들을 모두 대문자로 변환한다.

fun String.uppercase(): String

📍 lowercase()

String에 있는 대문자들을 소문자로 변환한다.

fun String.lowercase(): String

예시)

val lowerToUpper = "ABCdef"
println(lowerToUpper.uppercase()) // ABCDEF

val upperToLower = "ABCdef"
println(upperToLower.lowercase()) // abcdef

Char 알파벳 대문자 ↔️ 소문자 변환

📍 uppercaseChar()

대문자인 문자 하나를 소문자로 변환한다.

fun Char.uppercaseChar(): Char 

📍 lowercaseChar()

소문자인 문자 하나를 대문자로 변환한다.

fun Char.lowercaseChar(): Char 

예시)

val list = listOf('A','B','C','d','e','f')
val lowerToUpper = list.map { it.uppercaseChar() }
val upperToLower = list.map { it.lowerToUpper() }

println(lowerToUpper) // [A, B, C, D, E, F]
println(upperToLower) // [a, b, c, d, e, f]

문자열 처음, 끝 떼어내기

📍 removePrefix()

prefix를 떼어낸 String을 반환
String의 시작이 prefix와 일치하지 않으면 원본 String을 반환
원본 String을 파괴하지 않는다.

fun String.removePrefix(prefix: CharSequence): String

📍 removeSuffix()

removePrefix와 마찬가지

fun String.removeSuffix(suffix: CharSequence): String

📍 removeSurrounding()

delimiter를 prefix와 suffix로 동시에 가지면 prefix와 suffix를 제거한 String을 반환
prefix와 suffix 둘 중 하나라도 delimiter와 같지 않으면 아무일도 일어나지 않음
원본 String을 파괴하지 않는다.

fun String.removeSurrounding(delimiter: CharSequence): String
fun String.removeSurrounding(
    prefix: CharSequence,
    suffix: CharSequence
): String

예시)

val string = ".abc."
println(string.removePrefix(".")) // abc.
println(string.removePrefix("^")) // .abc.

println(string.removeSuffix(".")) // .abc
println(string.removeSuffix("^")) // .abc.

println(string.removeSurrounding(".")) // abc
println(string.removeSurrounding("^")) // .abc.
println(string.removeSurrounding(".", ".")) // abc
println(string.removeSurrounding(".", "^")) // .abc.
profile
잊고싶지 않은 것들을 기록해요✏️

0개의 댓글