Reputation: 2067
In Java, I want to get rid of the leading and trailing brackets in a String.
Given input:
"[ hello, char[]={a,b,c} ... bye ]"
How can I produce the output of
" hello, char[]={a,b,c} ... bye "
only the leading [
and trailing ]
is removed... How can I do that in Java?
Upvotes: 3
Views: 23485
Reputation: 106400
Take a look at the String.substring() method:
System.out.println(input.substring(1, input.length() - 1))
Upvotes: 2
Reputation: 639
String s = "[ hello, char[]={a,b,c} ... bye ]";
s = s.replaceAll("^\\[|\\]$", "");
in case of having leading and/or trailing whitespaces:
String s = " [ hello, char[]={a,b,c} ... bye ] ";
s = s.trim().replaceAll("^\\[|\\]$", "");
Upvotes: 5
Reputation: 10241
Infact,
this overload of substring(startIndex, endIndex);
input.substring(input.indexOf("[")+1,input.lastIndexOf("]"));
also if you want to remove the beginning and trailing spaces, use trim();
Upvotes: 3
Reputation: 35542
public class Test{
public static void main(String[] args){
String test = "[ abc ]";
System.out.println(test.substring(1,test.length()-1));
// Outputs " abc "
}
}
Upvotes: 7
Reputation: 96391
String i = "[ hello, char[]={a,b,c} ... bye ]";
int indexOfOpenBracket = i.indexOf("[");
int indexOfLastBracket = i.lastIndexOf("]");
System.out.println(i.substring(indexOfOpenBracket+1, indexOfLastBracket));
Prints:
hello, char[]={a,b,c} ... bye
Upvotes: 17
Reputation: 2080
String a = "[ hello, char[]={a,b,c} ... bye ] ";
a.substring(1,23);
System.out.println(a);
There you go i miss read.
Upvotes: 0