首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带句点、连字符或下划线的Java StringUtils.stripEnd

带句点、连字符或下划线的Java StringUtils.stripEnd
EN

Stack Overflow用户
提问于 2017-01-24 19:53:58
回答 1查看 3.5K关注 0票数 0

我试图使用StringUtils.stripEnd从字符串中删除尾随字符,并注意到如果我试图从"FOO_FOO"中删除"_FOO",这将返回一个空字符串。例如,

代码语言:javascript
复制
import org.apache.commons.lang3.StringUtils;

public class StripTest {

    public static void printStripped(String s1, String suffix){
        String result = StringUtils.stripEnd(s1, suffix);
        System.out.println(String.format("Stripping '%s' from %s  -->   %s", suffix, s1, result));
    }

    public static void main(String[] args) {
        printStripped("FOO.BAR", ".BAR");
        printStripped("BAR.BAR", ".BAR");
        printStripped("FOO_BAR", "_BAR");
        printStripped("BAR_BAR", "_BAR");
        printStripped("FOO-BAR", "-BAR");
        printStripped("BAR-BAR", "-BAR");
    }

}

哪种输出

代码语言:javascript
复制
Stripping '.BAR' from FOO.BAR  -->   FOO
Stripping '.BAR' from BAR.BAR  -->   
Stripping '_BAR' from FOO_BAR  -->   FOO
Stripping '_BAR' from BAR_BAR  -->   
Stripping '-BAR' from FOO-BAR  -->   FOO
Stripping '-BAR' from BAR-BAR  -->   

有人能解释一下这种行为吗?没有看到这个案子的任何文档中的示例。使用Java 7。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-24 20:03:52

查看StringUtils Javadoc中提供的文档和示例:

代码语言:javascript
复制
Strips any of a set of characters from the end of a String.

A null input String returns null. An empty string ("") input returns the empty string.

If the stripChars String is null, whitespace is stripped as defined by Character.isWhitespace(char).

 StringUtils.stripEnd(null, *)          = null
 StringUtils.stripEnd("", *)            = ""
 StringUtils.stripEnd("abc", "")        = "abc"
 StringUtils.stripEnd("abc", null)      = "abc"
 StringUtils.stripEnd("  abc", null)    = "  abc"
 StringUtils.stripEnd("abc  ", null)    = "abc"
 StringUtils.stripEnd(" abc ", null)    = " abc"
 StringUtils.stripEnd("  abcyx", "xyz") = "  abc"
 StringUtils.stripEnd("120.00", ".0")   = "12"

这不是你想要的,因为它会从结尾的任何地方剥去一组字符。我相信你在找removeEnd(...)

代码语言:javascript
复制
Removes a substring only if it is at the end of a source string, otherwise returns the source string.

A null source string will return null. An empty ("") source string will return the empty string. A null search string will return the source string.

 StringUtils.removeEnd(null, *)      = null
 StringUtils.removeEnd("", *)        = ""
 StringUtils.removeEnd(*, null)      = *
 StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
 StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
 StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
 StringUtils.removeEnd("abc", "")    = "abc"

removeEnd(...)操作的不是一组字符,而是一个子字符串,这正是您要提取的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41837780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档