I came up with the following method. But want inputs as to how to improve it and handle other scenarios.
The below method works only if the text always has the expected character at the first and last position in the string. Currently my need is to remove just the expected character. I am looking for more of a universal method that I can use with other characters too.
public class HelloWorld{
public static void main(String []args){
String txt = "[Today is a [good] day.]";
if ((txt.substring(0, 1).equals("["))
&& (txt.substring(txt.length() - 1).equals("]"))) {
txt = new StringBuilder(
txt.replaceFirst("[\\[]", "")).reverse().toString().replaceFirst(
"[\\]]", "");
txt = new StringBuilder(txt).reverse().toString();
}
System.out.println(txt);
}
}
- Can this method be improved to make it more efficient?
- How do I handle scenario where the first or last character is not the expected one? Any preexisting methods in java that I can use to address this issue?
[and]?txt = txt.substring(1, txt.length() - 1).