java - removing semi colon from a string if the string ends with it

后端 未结 12 1689
陌清茗
陌清茗 2020-12-29 08:20

I have a requirement in which I need to remove the semicolon if it is present at the end of the String(only at the end). I have tried the following code. But still it is not

相关标签:
12条回答
  • 2020-12-29 09:01

    Strings in java are immutable, so replaceAll returns a new string.

    Do

     text = text.replaceAll(";", "");
    
    0 讨论(0)
  • 2020-12-29 09:02

    You should not forget that String is immutable. So, whenever you want to modify it, you have to assign the result to a variable.

    A possible solution to what you need:

    if (text.endsWith(";") {
      text = text.substring(0, text.length() - 1);
    }
    
    0 讨论(0)
  • 2020-12-29 09:02
    public static void main(String[] args) {
        String text_original = "wherabouts;";
        char[] c = text_original.toCharArray();
    
        System.out.println("TEXT original: "+ text_original);
    
        String text_new = c[text_original.length()-1] == ';' ? text_original.substring(0,text_original.length()-2) : text_original;
    
        System.out.println("TEXT new: "+text_new);
    }
    
    0 讨论(0)
  • 2020-12-29 09:05
    text = text.replaceAll(";", "");
    

    Here's a little extra reading for you http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html

    0 讨论(0)
  • 2020-12-29 09:07
    if (text.endsWith(";")){
        text = text.substring(0,text.length()-1);
    }
    
    0 讨论(0)
  • 2020-12-29 09:12

    String is immutable so new String will be created after replace.

    String newString = text.replace(";", "");
    

    or

    String newString = text.replaceAll(";$", "");
    
    0 讨论(0)
提交回复
热议问题