String methods
- Kotlin course
- Beginner
- Lesson 32/116
- 4 min
Learn uppercase, lowercase and trim methods.
uppercase, lowercase, trim
To change case in Strings, use uppercase() and lowercase(). To strip leading and trailing spaces, call trim().
val s = "Hello"
println(s.uppercase()) // HELLO
println(s.lowercase()) // hello
val t = " Alex "
println(t.trim()) // AlexThese methods return a new String; the original is unchanged (Strings are immutable). So you must assign the result or use it directly.
Locale-specific characters are handled: "été".uppercase() gives "ÉTÉ".
Practice Use trim and uppercase
Write a fun main(). Assign " Alex " (spaces at both ends) to val s. Print s.trim() and s.trim().uppercase() on separate lines.
Starter code
fun main() {
// Clean the string and make it uppercase
}Sample solution
fun main() {
val s = " Alex "
println(s.trim())
println(s.trim().uppercase())
}Expected output
Alex ALEX
Method chaining
Multiple methods can be called back to back on a String; this is called chaining. Each call returns a String, so the next method applies to that result.
val s = " Hello "
val r = s.trim().uppercase()
println(r) // HELLOIt runs left to right: first trim() cuts spaces, then uppercase() makes it capital. Order matters; uppercase().trim() may give a different result.
Chaining keeps code short and readable; no intermediate variables needed.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does "hello".uppercase() return?
- hello
- Error
- Hello
- HELLO Correct answer
Explanation: uppercase turns all letters to capitals: HELLO.
2 Complete the uppercase call
val up = name.____()
val up = name.uppercase()
Explanation: name.uppercase() makes the string uppercase.
3 Match the methods
| Term | Meaning |
|---|---|
uppercase() |
Makes capitals |
lowercase() |
Makes small |
trim() |
Cuts spaces |
trim().uppercase() |
Clean and capitalize |