Remove a prefix (or suffix) from a string in Kotlin
This post will discuss how to remove a prefix (or suffix) from a string in Kotlin.
1. Using substring() function
The substring() function returns a substring of the string that starts at the specified index and continues till the end of the string. You can use it as follows to remove a prefix from a string using the startsWith() function.
|
1 2 3 4 5 6 7 8 9 10 |
fun removePrefix(s: String?, prefix: String?): String? { return if (s != null && prefix != null && s.startsWith(prefix)) { s.substring(prefix.length) } else s } fun main() { val s = "Superman" println(removePrefix(s, "Super")) // man } |
To remove a suffix from a string, you can use substring() function with the endsWith() function.
|
1 2 3 4 5 6 7 8 9 10 |
fun removeSuffix(s: String?, suffix: String?): String? { return if (s != null && suffix != null && s.endsWith(suffix)) { s.substring(0, s.length - suffix.length) } else s } fun main() { val s = "Superman" println(removeSuffix(s, "man")) // Super } |
2. Using split() function
Another solution is to split the string around the given prefix and return the second value of the resultant array. This can be easily done using the split() function.
|
1 2 3 4 5 6 7 8 9 10 |
fun removePrefix(s: String?, prefix: String): String? { return if (s != null && s.startsWith(prefix)) { s.split(prefix.toRegex(), 2)[1] } else s } fun main() { val s = "Superman" println(removePrefix(s, "Super")) // man } |
To remove a suffix from a string, split the string around the given suffix and return the first value of the resultant array.
|
1 2 3 4 5 6 7 8 9 10 |
fun removeSuffix(s: String?, suffix: String): String? { return if (s != null && s.endsWith(suffix)) { s.split(suffix.toRegex(), 2)[0] } else s } fun main() { val s = "Superman" println(removeSuffix(s, "man")) // Super } |
That’s all about removing a prefix (or suffix) from a Kotlin String.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)