I am trying to modify a String in such a way that it does not display the square braces as well as the character ‘,’ in it. The comma character actually may or may not be displayed in the String but I am not able to remove that.
public static String removeSquareBracesFromStringForPgNumberValidation(String string) {
StringBuilder str = new StringBuilder(string);
str.deleteCharAt(0);
str.deleteCharAt(string.length() - 2);
try {
str.toString().replace(",", "");
} catch (Exception e) {
e.printStackTrace();
}
return str.toString();
This is the code I am trying and if I pass "[5,055]" as an argument to this method, the output given is 5,055. The square braces are removed but the comma stays as it is. My expected output is 5055. The comma code I have added in try catch as it may or may not be displayed in the String which I pass as the argument. Please help me to achieve desired output.
>Solution :
str.toString() returns the current string content.
With str.toString().replace(",", "") you create a new String (String is final) without comma but you don’t use this value.
So you can directly return str.toString().replace(",", "");