- How to remove last N characters from string in Kotlin?
- Kotlin – Remove last N characters from string
- Examples
- 1. Remove last three characters from string
- 2. Number of characters to be removed > length of given string
- Conclusion
- Related Tutorials
- Kotlin program to remove first and last characters of a string
- String
- Constructors
- Properties
- length
- Functions
- compareTo
- equals
- get
- hashCode
- plus
- subSequence
- toString
How to remove last N characters from string in Kotlin?
In this tutorial, you shall learn how to remove last N characters from a given string in Kotlin, using String.dropLast() function, with examples.
Kotlin – Remove last N characters from string
To remove last N characters from a String in Kotlin, use String.dropLast() method.
Given a string str1 , and if we would like to remove last n characters from this string str1 , call dropLast() method on string str1 and pass the integer n as argument to the method as shown below.
dropLast() method returns a new string with the last n characters removed from the given string.
Examples
1. Remove last three characters from string
In this example, we will take a string in str1 , and drop the last 3 characters from the string str1 .
Kotlin Program
Original String : abcdefg Resulting String : abcd
2. Number of characters to be removed > length of given string
If the value of n is greater than the original string length, then dropLast() method returns an empty string.
Kotlin Program
Original String : abcdefg Resulting String :
Conclusion
In this Kotlin Tutorial, we learned how to remove last N characters from a given string using String.drop() method, with the help of Kotlin example programs.
Related Tutorials
- How to Check if String Ends with Specified Character in Kotlin?
- How to Check if String Ends with Specified String in Kotlin?
- How to Check if String Starts with Specified Character in Kotlin?
- How to Check if String Starts with Specified String Value in Kotlin?
- How to Check if Two Strings are Equal in Kotlin?
- How to Compare Strings in Kotlin?
- How to Compare Strings in Kotlin?
- How to Create an Empty String in Kotlin?
- How to Filter Characters of String in Kotlin?
- How to Filter List of Strings based on Length in Kotlin?
- How to Filter only Non-Empty Strings of Kotlin List?
- How to Filter only Strings from a Kotlin List?
- How to Get Character at Specific Index of String in Kotlin?
- How to Initialize String in Kotlin?
- How to Iterate over Each Character in the String in Kotlin?
- How to Remove First N Characters from String in Kotlin?
- How to check if a String contains Specified String in Kotlin?
- How to create a Set of Strings in Kotlin?
- How to define a List of Strings in Kotlin?
- How to define a String Constant in Kotlin?
- How to get Substring of a String in Kotlin?
- Kotlin String Concatenation
- Kotlin String Length
- Kotlin String Operations
- Kotlin String.capitalize() – Capitalize First Character
- Kotlin – Split String to Lines – String.lines() function
- Kotlin – Split String – Examples
- Kotlin – String Replace – Examples
- Kotlin – String to Integer – String.toInt()
- [Solved] Kotlin Error: Null can not be a value of a non-null type String
Kotlin program to remove first and last characters of a string
Kotlin provides different methods to manipulate a string. In this post, we will learn different Kotlin string methods to remove the first and last characters of a string.
drop takes one integer as its argument and removes the first characters from the string that we are passing as the argument. It returns one new string.
- n = 0 : It returns the same string
- n > 0 & n < string-length: removes the first n characters from the string and returns a new string.
- n < 0: Throws IllegalArgumentException
- n >= string-length : Returns one empty string
If its value is negative, it throws IllegalArgumentException.
fun main() val givenStr = "Hello World !!" println("drop(0) : $givenStr.drop(0)>") println("drop(6) : $givenStr.drop(6)>") println("drop(110) : $givenStr.drop(110)>") >
drop(0) : Hello World !! drop(6) : World !! drop(110) :
The last result is an empty string.
Similar to drop, dropLast is used to remove the last characters of a string. It takes one integer value as the parameter and removes the last characters of the string equal to that parameter. If it is negative, it throws IllegalArgumentException.
fun main() val givenStr = "Hello World !!" println(givenStr.dropLast(2)) >
This method removes all characters defined by the range. We can remove the start characters, end characters or middle characters using this method. For invalid index, it throws one IndexOutOfBoundsException. Note that the last index of the range is also removed.
For example, we can remove the first and the last characters of a string as like below :
fun main() val givenStr = "Hello World !!" println(givenStr.removeRange(0.rangeTo(5))) println(givenStr.removeRange(5 until givenStr.length)) >
removeRange(startIndex: Int, endIndex: Int) :
Another variant of removeRange. It removes all characters defined by the start and end index. If the indices are invalid, it throws NegativeArraySizeException. Note that the character at endIndex is not removed. All characters before it are removed.
fun main() val givenStr = "Hello World !!" println(givenStr.removeRange(0,5)) >
Convert to a StringBuilder and use removeRange :
removeRange methods are also available in StringBuilder class. The definitions are the same as we have seen for strings. We can convert a string to a StringBuilder and use these methods to remove start or ending characters.
fun main() val givenStr = "Hello World !!" println(StringBuilder(givenStr).removeRange(0,6).toString()) >
String
Класс String представляет символьные строки. Все строковые литералы в программах Kotlin, такие как «abc» , реализованы как экземпляры этого класса.
Constructors
Класс String представляет символьные строки. Все строковые литералы в программах Kotlin, такие как «abc» , реализованы как экземпляры этого класса.
Properties
length
Возвращает длину этой последовательности символов.
Functions
compareTo
Сравнивает этот объект с указанным объектом для заказа. Возвращает ноль, если этот объект равен указанному другому объекту, отрицательное число, если оно меньше другого , или положительное число, если оно больше другого .
fun compareTo(other: String): Int
equals
Указывает на то,что какой-то другой объект «равен» этому.Введение должно отвечать следующим требованиям:
fun equals(other: Any?): Boolean
get
Возвращает символ этой строки по указанному индексу .
hashCode
Возвращает значение хэш-кода для объекта. Общий контракт hashCode :
plus
Возвращает строку, полученную путем объединения этой строки со строковым представлением данного другого объекта.
operator fun plus(other: Any?): String
subSequence
Возвращает новую последовательность символов, которая является подпоследовательностью этой последовательности символов, начиная с указанного startIndex и заканчивая прямо перед указанным endIndex .
fun subSequence(startIndex: Int, endIndex: Int): CharSequence
toString
Возвращает строковое представление объекта.