62

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(".", "")
}
5
  • You say you are trying to add/remove comma, yet your code implies you are adding/removing dot. Commented Mar 18, 2018 at 3:14
  • Sorry my fault. If you look at the code you can see that if there is no "." in the string, it should add one to the string, but if there already is one, he should remove it. Commented Mar 18, 2018 at 3:20
  • Unclear what you are asking. Commented Mar 18, 2018 at 3:20
  • My question is how do I remove the "."? // I added my git to the question, maybe that helps Commented Mar 18, 2018 at 3:23
  • Replace is not the good way to remove a char or sequence in a string: use filter in place of replace Commented Nov 1, 2019 at 0:51

2 Answers 2

98

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(".", "")
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, that solved my problem and explained it well!
19

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 }

7 Comments

The 1st exemple didn't compile anymore. I added ".get(0)"
This should be preferred over the accepted answer. Nice answer!
why not just ".filterNot { it == '.' }"
@Xan You will see a lint error that says "Operator == cannot be applied to Char and String".
@YUSMLE you spiked to @ Xan about my solution or???
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.