[英]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);
}
}
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.