Ron*_*nin 2 java string substring
在Java中,我想摆脱String中的前导括号和尾随括号.
给定输入:
"[ hello, char[]={a,b,c} ... bye ]"
Run Code Online (Sandbox Code Playgroud)
我怎样才能产生输出
" hello, char[]={a,b,c} ... bye "
Run Code Online (Sandbox Code Playgroud)
只删除了前导[和尾随]...我怎么能用Java做到这一点?
Jam*_*sev 16
String i = "[ hello, char[]={a,b,c} ... bye ]";
int indexOfOpenBracket = i.indexOf("[");
int indexOfLastBracket = i.lastIndexOf("]");
System.out.println(i.substring(indexOfOpenBracket+1, indexOfLastBracket));
Run Code Online (Sandbox Code Playgroud)
打印:
hello, char[]={a,b,c} ... bye
Run Code Online (Sandbox Code Playgroud)
public class Test{
public static void main(String[] args){
String test = "[ abc ]";
System.out.println(test.substring(1,test.length()-1));
// Outputs " abc "
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
String s = "[ hello, char[]={a,b,c} ... bye ]";
s = s.replaceAll("^\\[|\\]$", "");
Run Code Online (Sandbox Code Playgroud)
如果有前导和/或尾随空格:
String s = " [ hello, char[]={a,b,c} ... bye ] ";
s = s.trim().replaceAll("^\\[|\\]$", "");
Run Code Online (Sandbox Code Playgroud)