String.replace() / trim()
Functions for replacing specific parts of a string, or removing whitespace and specified characters from the beginning and end of a string.
Syntax
// Replaces part of a string. str.replace(oldValue: String, newValue: String, ignoreCase: Boolean = false) // Removes whitespace from both ends of a string. str.trim() str.trimStart() // Leading whitespace only str.trimEnd() // Trailing whitespace only
Method List
| Method | Description |
|---|---|
| replace(oldValue, newValue, ignoreCase) | Replaces all occurrences of the matching string. You can specify whether the match is case-sensitive. |
| replace(regex: Regex, replacement: String) | Replaces all parts of the string that match the given regular expression. |
| replaceFirst(oldValue, newValue) | Replaces only the first occurrence of the matching string. |
| trim() | Removes all whitespace characters (spaces, tabs, newlines, etc.) from both ends of the string. |
| trimStart() | Removes whitespace characters from the beginning of the string only. |
| trimEnd() | Removes whitespace characters from the end of the string only. |
| trim(predicate) | Removes characters from both ends that match the condition specified by a lambda. |
Sample Code
fun main() {
// Replace a specific string.
val text = "Hello, World! Hello, Kotlin!"
val replaced = text.replace("Hello", "Hi")
println(replaced) // Hi, World! Hi, Kotlin!
// Replace while ignoring case.
val noCase = text.replace("hello", "Hey", ignoreCase = true)
println(noCase) // Hey, World! Hey, Kotlin!
// Replace only the first occurrence.
val firstOnly = text.replaceFirst("Hello", "Greetings")
println(firstOnly) // Greetings, World! Hello, Kotlin!
// Replace using a regular expression.
val digits = "abc123def456"
val noDigits = digits.replace(Regex("[0-9]+"), "#")
println(noDigits) // abc#def#
// Remove whitespace from both ends.
val padded = " Kotlin "
println(padded.trim()) // "Kotlin"
println(padded.trimStart()) // "Kotlin "
println(padded.trimEnd()) // " Kotlin"
// Remove characters matching a condition.
val slashed = "///path/to/file///"
println(slashed.trim('/')) // path/to/file
}
Notes
『replace()』replaces all occurrences of a matching substring with a new string. By default, the match is case-sensitive, but you can pass 『ignoreCase = true』 to make it case-insensitive. To use a regular expression, pass a 『Regex』 object as the first argument.
『trim()』removes whitespace characters — spaces, tabs, newlines, and so on — by default. You can pass a lambda to specify a custom condition for which characters to remove. All of these methods return a new string; the original string is not modified. Strings in Kotlin are immutable.
If you find any errors or copyright issues, please contact us.