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

后端 未结 12 1852
陌清茗
陌清茗 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:22

    Solution for only one semi-colon

    // Don't use regular expressions if you don't need to.
    if (text.endsWith(";")) {
        text = text.substring(0, text.length() - 1);
    }
    

    Slower solution for possibly more than one semi-colon

    text.replaceAll(";+$", "");
    

    Additionally, here are some other problems with the code you originally posted, for reference.

    if(text.substring(text.length()-1) == ";"){
    

    You can't compare strings with ==. Instead, you have to compare them with .equals(). This would be correctly written like this ...ength()-1).equals(";").

    text.replaceAll(";", "");
    

    This replaces all semicolons it finds. This means that if your string was some;thing;, it would turn it into something, but you want to only remove the last semicolon, like this: some;thing. To do this correctly, you need to look for the end of the string, using the special $ character like this:

    text.replaceAll(";$", "");
    

提交回复
热议问题