'Remove character from string in Kotlin
I am trying to create an Android calculator which uses strings in Kotlin. My problem is how do I delete a comma (or the negative) if it already contains one.
Here is my code, it adds the comma correctly but doesn't delete it if user clicks again:
if (!buClickValue.contains(".")) {
buClickValue += "."
} else {
buClickValue.replace(".", "")
}
}
or here is my Github
Solution 1:[1]
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(".", "")
Solution 2:[2]
The more logical technic is not to replace but to filter
buClickValue = buClickValue.filterNot { it == "."[0] }
or
buClickValue = buClickValue.filterNot { it == '.' }
Or to extend
filtered = ".,;:"
buClickValue = buClickValue.filterNot { filtered.indexOf(it) > -1 }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ameya Pandilwar |
| Solution 2 |
