修剪Java中的字符

Qui*_*Par 56 java string trim

如何修剪Java中的字符?
例如

String j = “\joe\jill\”.Trim(new char[] {“\”});
Run Code Online (Sandbox Code Playgroud)

j应该是

"乔\吉尔"

String j = “jack\joe\jill\”.Trim("jack");
Run Code Online (Sandbox Code Playgroud)

j应该是

"\乔\吉尔\"

等等

Col*_*son 84

Apache Commons有一个很棒的StringUtils类(org.apache.commons.lang.StringUtils).在StringUtils有一个strip(String, String)会做你想要什么方法.

我强烈建议使用Apache Commons,尤其是Collections和Lang库.


Pau*_*des 41

这样做你想要的:

public static void main (String[] args) {
    String a = "\\joe\\jill\\";
    String b = a.replaceAll("\\\\$", "").replaceAll("^\\\\", "");
    System.out.println(b);
}
Run Code Online (Sandbox Code Playgroud)

$用于去除在字符串的末尾序列.将^用于在beggining删除.

作为替代方案,您可以使用以下语法:

String b = a.replaceAll("\\\\$|^\\\\", "");
Run Code Online (Sandbox Code Playgroud)

|手段"或".

如果你想修剪其他字符,只需调整正则表达式:

String b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining
Run Code Online (Sandbox Code Playgroud)


Cow*_*wan 18

CharMatcher - 谷歌番石榴

在过去,我是第二个科林斯的阿帕奇公共答案.但是现在已经发布了Google的guava-libraries,CharMatcher类可以很好地完成你想要的:

String j = CharMatcher.is('\\').trimFrom("\\joe\\jill\\"); 
// j is now joe\jill
Run Code Online (Sandbox Code Playgroud)

CharMatcher有一套非常简单而强大的API以及一些预定义的常量,这使得操作变得非常容易.例如:

CharMatcher.is(':').countIn("a:b:c"); // returns 2
CharMatcher.isNot(':').countIn("a:b:c"); // returns 3
CharMatcher.inRange('a', 'b').countIn("a:b:c"); // returns 2
CharMatcher.DIGIT.retainFrom("a12b34"); // returns "1234"
CharMatcher.ASCII.negate().removeFrom("a®¶b"); // returns "ab";
Run Code Online (Sandbox Code Playgroud)

非常好的东西.


jak*_*eld 7

这是另一个非regexp,非超级棒,非超级优化,但非常容易理解的非外部lib解决方案:

public static String trimStringByString(String text, String trimBy) {
    int beginIndex = 0;
    int endIndex = text.length();

    while (text.substring(beginIndex, endIndex).startsWith(trimBy)) {
        beginIndex += trimBy.length();
    } 

    while (text.substring(beginIndex, endIndex).endsWith(trimBy)) {
        endIndex -= trimBy.length();
    }

    return text.substring(beginIndex, endIndex);
}
Run Code Online (Sandbox Code Playgroud)

用法:

String trimmedString = trimStringByString(stringToTrim, "/");
Run Code Online (Sandbox Code Playgroud)