0

I have string variable where at certain times the variable has "+" or "#" characters at the end of the string. I want to remove these characters from the end of the string. I wrote the following code but it doesn't work. The code compiles and the else command works but the if and if else statements do not work. Thank you for your help

if (konHamle.contains("+") ) 
{
    int kont1 = konHamle.indexOf("+");
    hamHamle = konHamle.substring(0, konHamle.length() - 1);
    break;
} 
else 
{
    hamHamle = konHamle;
    break;

}
6
  • 4
    Define do not work. Commented Dec 17, 2015 at 18:52
  • 1
    The solution to stackoverflow.com/questions/4576352/… might be of use to you. Can the characters you want to remove appear anywhere else, or only at the end? Commented Dec 17, 2015 at 18:54
  • 1
    I would try hamHamle = konHamle.substring(0, konHamle.lastIndexOf("+") - 1); Commented Dec 17, 2015 at 18:54
  • By relieving I meant getting rid of the character... Regards.. Commented Dec 17, 2015 at 18:58
  • Only at the end... Thank you Commented Dec 17, 2015 at 19:39

3 Answers 3

3

This is much simpler using String.endsWith():

if (konHamle.endsWith("+")){
    konHamle = konHamle.substring(0, konHamle.length() - 1);
}

Or even shorter (less readable though):

 konHamle = konHamle.endsWith("+") ? konHamle.substring(0, konHamle.length() - 1) : konHamle;
Sign up to request clarification or add additional context in comments.

1 Comment

I2ll check and let you know. Regards,
0

indexOf gives you the first occurence, hence your code might not be working

Try regex. $ marks the end of line, this will also handle multiple characters like # and + as mentioned in the question.

konHamle = konHamle.replaceAll("[#+]$", "");

Comments

0

You can use substring method of String.

public String removeLastPlusMethod(String str) {
    if (str.length() > 0 && str.charAt(str.length()-1)=='+') {
      str = str.substring(0, str.length()-1);
    }
    return str;
}

You can also use endsWith method to check the last character of a string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.