Search

String

JVM에서 String 타입은 문자당 약 2바이트를 사용한다.
String 타입으로 나타냄
“” 를 통해 문자열을 표현
String은 불변이다. 모든 연산들은 원본 String을 변환하여 새로운 String을 만들어 리턴
val str = "abcd" // Creates and prints a new String object println(str.uppercase()) // ABCD // The original string remains the same println(str) // abcd
Kotlin
복사
+ 를 통해 문자열을 이어 붙일 수 있음
val s = "abc" + 1 println(s + "def") // abc1def
Kotlin
복사
인덱스 연산 s[i] 를 통해 문자열의 각 문자에 접근 가능
for문을 통해서도 문자열의 각 문자에 접근 가능
for (c in str) { println(c) }
Kotlin
복사

문자열 리터럴

escaped 문자를 포함할 수 있음
val s = "Hello, world!\n"
Kotlin
복사

다중줄 문자열

“”” 를 통해 개행 문자나 임의의 텍스트를 포함할 수 있음 (escaped 문자 미포함)
val text = """ for (c in "foo") print(c) """
Kotlin
복사
trimMargin()을 통해 선행 공백을 제거할 수 있음
val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """.trimMargin()
Kotlin
복사

문자열 템플릿

$ 를 통해 “” 안에 변수를 표현할 수 있음
$ 에 {} 를 사용하면 “” 안에 표현식을 넣을 수 있음
val customers = 10 println("There are $customers customers") // There are 10 customers println("There are ${customers + 1} customers") // There are 11 customers
Kotlin
복사

문자열 포맷팅

format() 은 문자열을 형식 지정자를 통해 formatting 할 수 있음
// Formats an integer, adding leading zeroes to reach a length of seven characters val integerNumber = String.format("%07d", 31416) println(integerNumber) // 0031416 // Formats a floating-point number to display with a + sign and four decimal places val floatNumber = String.format("%+.4f", 3.141592) println(floatNumber) // +3.1416 // Formats two strings to uppercase, each taking one placeholder val helloString = String.format("%S %S", "hello", "world") println(helloString) // HELLO WORLD // Formats a negative number to be enclosed in parentheses, then repeats the same number in a different format (without parentheses) using `argument_index$`. val negativeNumberInParentheses = String.format("%(d means %1\$d", -31416) println(negativeNumberInParentheses) //(31416) means -31416
Kotlin
복사