2

I have a string like this:

String line="[x1,x2,x3]";

I want to remove both of the square brackets from the String (replace them with an empty string). I tried it like this:

 String x=line.replace("[","").replace("]","");

Is there a more efficient way than this?

5
  • 1
    what's wrong with your current solution ? Although, you could shrink it up to one line. Commented Mar 17, 2017 at 7:54
  • That's looks like the empty string rather than null - please clarify. x=line.replaceAll("^\\[|\\]$", ""). Commented Mar 17, 2017 at 7:54
  • 1
    Are your brackets always at the beginning and end of the string like that? Are they always present? Commented Mar 17, 2017 at 8:02
  • brackets are always at the beginning and end of the String Commented Mar 17, 2017 at 8:06
  • @Navoda and are they always present? And is this the only place they appear? Commented Mar 17, 2017 at 8:07

5 Answers 5

2

String is immutable so you can

String x = line.replace("[","").replace("]","");

another more efficient way is using regex with a pattern for both [ and ]

like

String x = line.replaceAll("[\\]\\[]+", "");
Sign up to request clarification or add additional context in comments.

Comments

2

You may use .replaceAll if you want to use a regex to remove both [ and ] at the same time anywhere inside the string (actually, the equivalent of OP two line code snippet):

String x = line.replaceAll("[\\]\\[]+", "");

The [\]\[]+ pattern matches one or more (+) [ or ] characters (these must be escaped inside [....], a character class).

Java demo:

String line="[x1,x2,x3]";
String x = line.replaceAll("[\\[\\]]+", "");
System.out.println(x);
// => x1,x2,x3

Comments

1

If the brackets are always present, and always at the start and end of the string as shown in the example, you can just use substring:

String x2 = line.substring(1, line.length()-1);

Comments

0

Another way:

line = line.substring(1, line.length()-1);

If you want to preserve the square brackets that comes in between, then you can use:

String line="[x1,[x2],x3]";
line = line.replaceAll("^\\[(.*)\\]$", "$1");

Output

x1,[x2],x3

Comments

0

If brackets can only appear at the beginning and at the end of the string, the fastest method (in terms of performance) would be using substring which does not involve regular expressions.

If brackets are guaranteed to be present:

line = line.substring(1, line.length()-1);

If brackets are optional:

int len = line.length();
int trimStart = (len > 0 && line.charAt(0) == '[') ? 1 : 0;
int trimEnd = (len > 0 && line.charAt(len-1) == ']') ? 1 : 0;
if (trimStart > 0 || trimEnd > 0) {
    line = line.substring(trimStart, len - trimEnd);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.