Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove a character from a transformed String which may come or may not come in a String

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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(",", "");

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading