简体   繁体   English

StringUtils重载斩波方法

[英]StringUtils Overload chop method

I want to overload the chop method of StringUtils to remove the last character if it is a backslash (\\) . 我想重载StringUtils的chop方法以删除最后一个字符(如果它是反斜杠(\\)

Is it possible to overload the function or I need to use an if condition? 是否可以重载该函数,或者我需要使用if条件?

为什么不这样做呢?

StringUtils.removeEnd(s,"\\")

yes, use an if statement. 是的,使用if语句。 You can't override a static method and it would be too much anyway to create it's own class just for that. 您不能覆盖静态方法,为此仅创建它自己的类将是太多了。

I have an alternative that I personally like: 我个人喜欢其他选择:

public static String chopIf(Predicate<String> p, String s) {
    if (p.test(s)) {
        return s.substring(0, s.length()-1); //or StringUtils.chop(s)
    }
    return s;
}

public static void main(String[] args) {
    String test = "qwert\\";
    System.out.println(chopIf(s -> s.endsWith("\\"), test));
}

Something like that. 这样的事情。 Then you can use it for any character. 然后,您可以将其用于任何字符。 Tweak it according to need. 根据需要进行调整。

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

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