Mohamed-Ali Elakhrass
Mohamed-Ali Elakhrass

Reputation: 95

StringUtils Overload chop method

I want to overload the chop method of StringUtils to remove the last character if it is a backslash(\).

Is it possible to overload the function or I need to use an if condition?

Upvotes: 1

Views: 1565

Answers (2)

Matthew McPeak
Matthew McPeak

Reputation: 17924

Why not this instead?

StringUtils.removeEnd(s,"\\")

Upvotes: 4

Jack Flamp
Jack Flamp

Reputation: 1233

yes, use an if statement. 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.

Upvotes: 3

Related Questions