简体   繁体   English

如何在Java中删除字符串中的第一个和最后一个字符?

[英]How to remove first and last character in a string in Java?

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?我可以使用 Java 中任何预先存在的方法来解决这个问题吗?

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). (检查前缀和后缀长度的总和是为了避免使用重叠的前缀和后缀进行修剪)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM