Reputation: 404
I have a small problem with the minus operation in java. When the user press the 'backspace' key, I want the char the user typed, to be taken away from the word which exists. e.g word = myname and after one backspace word = mynam
This is kinda of what I have:
String sentence = "";
char c = evt.getKeyChar();
if(c == '\b') {
sentence = sentence - c;
} else {
sentence = sentence + c;
}
The add operation works. So if I add a letter, it adds to the existing word. However, the minus isn't working. Am I missing something here? Or doing it completely wrong?
Upvotes: 14
Views: 74854
Reputation: 224905
Strings don’t have any kind of character subtraction that corresponds to concatenation with the +
operator. You need to take a substring from the start of the string to one before the end, instead; that’s the entire string except for the last character. So:
sentence = sentence.substring(0, sentence.length() - 1);
Upvotes: 15
Reputation: 8471
You should investigate the StringBuilder class, eg:
StringBuilder sentence = new StringBuilder();
Then you can do something like:
sentence.append(a);
for a new character or
sentence.deleteCharAt(sentence.length() - 1);
Then when you actually want to use the string, use:
String s = sentence.toString();
Upvotes: 0
Reputation: 2476
sentance = sentance.substring(0, sentance.length() - 1);
There is no corresponding operator to + which allows you to delete a character from a String.
Upvotes: 0
Reputation: 86391
For convenience, Java supports string concatenation with the '+' sign. This is the one binary operator with a class type as an operand. See String concatenation operator in the Java Language Specification.
Java does not support an overload of the '-' operator between a String and a char.
Instead, you can remove a character from a string by adding the substrings before and after.
Upvotes: 1