Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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 getting replaced. Can anyone please tell what I need to change in the following code in the line number
(I referred the code from here How do I delete specific characters from a particular String in Java?)

public static void main(String[] args) {
    String text = "wherabouts;";
    System.out.println("SSS "+text.substring(text.length()-1));
    if(text.substring(text.length()-1) == ";"){
        text.replaceAll(";", "");
    }
    System.out.println("TEXT : "+text);
}
like image 583
user1732653 Avatar asked Oct 09 '12 18:10

user1732653


4 Answers

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

Since Strings in Java are immutable, so replaceALl() method doesn't do the in-place replacement, rather it returns a new modified string. So, you need to store the return value in some other string. Also, to match the semi-colon at the end, you need to use $ quantifier after ;

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

$ denotes the end of the string since you want to replace the last semi-colon..

If you don't use $, it will replace all the ; from your strings..

Or, for your job, you can simply use this, if you want to remove the last ;:

    if (text.endsWith(";")) {
        text = text.substring(0, text.length() - 1);
        System.out.println(text);
    }

UPDATE: And, if there are more semi-colons at the end:

text = text.replaceAll(";+$", "");
like image 200
Rohit Jain Avatar answered Nov 18 '22 14:11

Rohit Jain


String modifiedText = text.replaceAll(";$", "");

OR

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

OR

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

NOTE:

Strings are immutable. That means you can't change them.

Therefore you have to either re-assign text or set it to a new variable.

like image 31
jahroy Avatar answered Nov 18 '22 12:11

jahroy


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

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

like image 43
Louis Ricci Avatar answered Nov 18 '22 13:11

Louis Ricci


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);
}
like image 3
Dan D. Avatar answered Nov 18 '22 13:11

Dan D.