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;

}
brso05
  • 13,142
  • 2
  • 21
  • 40
Otag
  • 141
  • 11

3 Answers3

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;
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
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.

RockAndRoll
  • 2,247
  • 2
  • 16
  • 35
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("[#+]$", "");
sidgate
  • 14,650
  • 11
  • 68
  • 119