I am trying to create an Android calculator which uses strings in Kotlin. I do not know how to delete a comma (or the negative) if it already contains one.
Here is my code which adds the comma correctly but doesn't delete it if the user clicks again:
if (!buClickValue.contains(".")) {
buClickValue += "."
} else {
buClickValue.replace(".", "")
}
To remove first N characters from a String in Kotlin, use String. drop() method.
You can remove part of the string by replacing it with empty string, but note that this will keep any surrounding characters including the surrounding spaces.
You can use drop() of String class to remove first char of string.
How to Remove Last N Characters from String in Kotlin? 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.
In this tutorial, we will learn different ways to do that in Kotlin. One way to solve this is by getting the substrings before and after the give index. Put the new character in between them and it will give the new string. We will use string.substring method to get one substring :
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.
toRegex () method is used to convert one string to a regular expression. replace method is used to replace all characters matched by that regex with space. filter is another way to remove unwanted characters from a string.
The replace()
method is designed to return the value of the new String
after replacing the characters. In your case, the value obtained after replacing the characters is never reassigned back to the original variable.
Specifically in your else clause, the line should be changed to -
buClickValue = buClickValue.replace(".", "")
The more logical technic is not to replace but to filter
buClickValue = buClickValue.filterNot { it == "."[0]) }
Or to extend
filtered = ".,;:" buClickValue = buClickValue.filterNot { filtered.indexOf(it) > -1 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With