Reputation: 85
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.
Upvotes: 0
Views: 41
Reputation: 339482
The Answer by Warminski is correct.
Another approach is to filter a stream of the code point integer numbers that represent each character in the input string.
We want to filter out 44 for COMMA, 91 for LEFT SQUARE BRACKET, and 93 for RIGHT SQUARE BRACKET.
final int LEFT = "[".codePointAt( 0 ) ; // 91.
final int COMMA = ",".codePointAt( 0 ) ; // 44.
final int RIGHT = "]".codePointAt( 0 ) ; // 93.
String result =
"[5,055]"
.codePoints()
.filter( codePoint -> ! ( ( codePoint == LEFT ) || ( codePoint == COMMA ) || ( codePoint == RIGHT ) ) )
.collect( StringBuilder::new , StringBuilder::appendCodePoint , StringBuilder::append )
.toString()
;
See this code run live at IdeOne.com.
5055
Upvotes: 0
Reputation: 1835
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(",", "");
Upvotes: 1