Remove characters from the start of a string in Kotlin
This article explores different ways to remove characters from the start of a string in Kotlin.
Since strings are immutable in Kotlin, we can’t remove characters from it. However, we can create a new string with the first n characters removed. This can be done using the substring() function with the starting index n, which creates a substring starting from position n till its end.
|
1 2 3 4 5 6 |
fun main() { val s = "Hello Google" val n = 6 println(s.substring(n)) // Google } |
If the index is negative or larger than the length of the string, the string index out of range exception is thrown. This can be handled by placing the range check before the substring() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun removefirstNchars(s: String?, n: Int): String? { return if (s == null || s.length < n) { s } else s.substring(n) } fun main() { val s = "Hello Google" val n = 6 println(removefirstNchars(s, n)) // Google } |
It is often required to pop a character from the beginning of the string if and only if it matches with the specific character. This can be implemented as follows in Kotlin.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun removeFirstChar(s: String?, c: Char): String? { if (s == null || s.isEmpty()) { return s } return if (s.startsWith(c)) { s.substring(1) } else s } fun main() { val s = "ABC" val c = 'A' println(removeFirstChar(s, c)) // AB } |
That’s all about removing characters from the start of a string in Kotlin.
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 :)