0

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?
8
  • 3
    The code seems to be doing a lot of unnecessary things, but it's unclear what it's supposed to do? Remove the first and last character if they're [ and ]? Commented Apr 2, 2020 at 14:04
  • 2
    @jiveturkey don't recommend that site, the tutorials are mostly cr*p. Commented Apr 2, 2020 at 14:06
  • 2
    txt = txt.substring(1, txt.length() - 1). Commented Apr 2, 2020 at 14:06
  • 1
    @jiveturkey I think you mean kayaman. Commented Apr 2, 2020 at 14:10
  • 1
    Ok. I've been warned :) Check this out instead. docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html Commented Apr 2, 2020 at 14:17

1 Answer 1

3

Your approach seems wildly complicated:

if (txt.startsWith("[") && txt.endsWith("]")) {
  txt = txt.substring(1, txt.length() - 1);
}

For more general prefix and suffix:

if (txt.startsWith(prefix) && txt.endsWith(suffix) && txt.length() >= prefix.length() + suffix.length()) {
  txt = txt.substring(prefix.length(), txt.length() - suffix.length());
}

(The check on the sum of the prefix and suffix length is to avoid trimming with overlapping prefix and suffix).

Sign up to request clarification or add additional context in comments.

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.