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);
}
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;$denotes the end of the string since you want to replace the lastsemi-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
;:UPDATE: And, if there are more semi-colons at the end: