1. Overview
1.概述
In this quick tutorial, we’re going to explore different techniques for removing the last character of a String.
在这个快速教程中,我们将探讨去除字符串最后一个字符的不同技术。
2. Using String.substring()
2.使用String.substring()
The easiest way is to use the built-in substring() method of the String class.
最简单的方法是使用substring()类的内置方法。
In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character. We can achieve that by calling String‘s length() method, and subtracting 1 from the result.
为了删除一个给定字符串的最后一个字符,我们必须使用两个参数。0作为起始索引,以及倒数第二个字符的索引。我们可以通过调用String的length()方法,并从结果中减去1来实现。
However, this method isn’t null-safe, and if we use an empty string, this is going to fail.
然而,这个方法不是空安全的,如果我们使用一个空字符串,这将会失败。
To overcome issues with null and empty strings, we can wrap the method in a helper class:
为了克服空字符串的问题,我们可以将该方法包装在一个辅助类中。
public static String removeLastChar(String s) {
return (s == null || s.length() == 0)
? null
: (s.substring(0, s.length() - 1));
}
We can refactor the code, and use Java 8:
我们可以重构代码,并使用Java 8。
public static String removeLastCharOptional(String s) {
return Optional.ofNullable(s)
.filter(str -> str.length() != 0)
.map(str -> str.substring(0, str.length() - 1))
.orElse(s);
}
3. Using StringUtils.substring()
3.使用StringUtils.substring()
Instead of reinventing the wheel, we can use the StringUtils class from the Apache Commons Lang3 library, which offers helpful String operations. One of them is a null-safe substring() method, which handles exceptions.
我们可以使用Apache Commons Lang3库中的StringUtils类,它提供了有用的String操作,而不是重新发明车轮。其中一个是空安全的substring()方法,可以处理异常。
To include StringUtils, we have to update our pom.xml file:
为了包括StringUtils,我们必须更新我们的pom.xml文件。
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
StringUtils.substring() requires three parameters: a given String, an index of the first character (in our case it will be 0 always), and the index of the penultimate character. Again, we can simply use the length() method and subtract 1:
StringUtils.substring()需要三个参数:一个给定的String,第一个字符的索引(在我们的例子中它总是0),以及倒数第二个字符的索引。同样,我们可以简单地使用length()方法并减去1:。
String TEST_STRING = "abcdef";
StringUtils.substring(TEST_STRING, 0, TEST_STRING.length() - 1);
Yet again, this operation isn’t null-safe. It’ll work fine with empty Strings though.
然而,这个操作并不是空安全的。但对于空的字符串,它可以正常工作。
4. Using StringUtils.chop()
4.使用StringUtils.chop()
The StringUtils class provides the chop() method, which works well with all edge scenarios: empty and null Strings.
StringUtils类提供了chop()方法,它能很好地处理所有的边缘情况:空字符串和空字符串。
It’s very easy to use, and requires only one parameter: the String. Its sole purpose is to remove the last character, nothing more, nothing less:
它非常容易使用,只需要一个参数:String.它的唯一目的是删除最后一个字符,仅此而已。
StringUtils.chop(TEST_STRING);
5. Using Regular Expression
5.使用正则表达式
We can also remove the last character (or any number of characters) from a String by making good use of regular expressions.
我们还可以通过善用正则表达式,从String中删除最后一个字符(或任何数量的字符)。
For example, we can use the replaceAll() method of the String class itself, which takes two parameters: the regular expression and the replacement String:
例如,我们可以使用String类本身的replaceAll()方法,它需要两个参数:正则表达式和替换String。
TEST_STRING.replaceAll(".$", "");
Note that, because we’re calling a method on the String, the operation isn’t null-safe.
请注意,由于我们正在调用String的方法,操作并不是空安全的。
Also, replaceAll() and regex expressions can be complex at first sight. We can read more about regex here, but to make the logic a bit more user-friendly, we can wrap it in a helper class:
另外,replaceAll()和regex表达式乍看之下可能很复杂。我们可以在这里阅读更多关于regex的内容,但是为了使逻辑更加人性化,我们可以将其封装在一个辅助类中。
public static String removeLastCharRegex(String s) {
return (s == null) ? null : s.replaceAll(".$", "");
}
Note that if a String ends with a newline, then the above method will fail as “.” in regex matches for any character except for line terminators.
请注意,如果一个字符串以换行符结束,那么上述方法将失败,因为“.”在重构函数中匹配任何字符,除了行结束符。
Finally, let’s re-write the implementation with Java 8:
最后,让我们重新写一下用Java 8实现。
public static String removeLastCharRegexOptional(String s) {
return Optional.ofNullable(s)
.map(str -> str.replaceAll(".$", ""))
.orElse(s);
}
6. Conclusion
6.结论
In this brief article, we discussed different ways of removing only the last character of a String, some manual and some ready out of the box.
在这篇简短的文章中,我们讨论了只删除字符串最后一个字符的不同方法,有些是手动的,有些是开箱即用。
If we need more flexibility, and we need to remove more characters, we can use the more advanced solution with regular expressions.
如果我们需要更多的灵活性,需要删除更多的字符,我们可以使用正则表达式的更高级解决方案。
As always, the code used throughout the article can be found over on GitHub.
一如既往,文章中所使用的代码可以在GitHub上找到over。