views:

155

answers:

2

In an Android app, I am looking for the functionality of the .NET string function [Trim('aaa')] which will trim off the text "aaa" off a string. I don't think this is natively available in Java and I haven't seen that functionality in Android Java textutil library.

Is there an easy way to have a Java app trim a set of characters from the string?

+5  A: 

Use trim or replaceAll.

thelost
+2  A: 

Regex trimming

The specification isn't clear, but you can use regular expression to do this.

Here's an example:

    // trim digits from end
    System.out.println(
        "123a456z789".replaceAll("\\d+\\Z", "")
    );
    // 123a456z

    // trim digits from beginning
    System.out.println(
        "123a456z789".replaceAll("\\A\\d+", "")
    );
    // a456z789

    // trim digits from beginning and end
    System.out.println(
        "123a456z789".replaceAll("\\A\\d+|\\d+\\Z", "")
    );
    // a456z

The anchors \A and \Z match the beginning and end of the input respectively. | is alternation. \d is the shorthand for the digit character class. + is "one-or-more-of" repetition specifier. Thus, the pattern \d+\Z is regex-speak for "sequence of digits at the end of the input".

References


Literal trimming

If you just want a literal suffix/prefix chopping, then no regex is required. Here's an example:

public static String chopPrefix(String s, String prefix) {
    if (s.startsWith(prefix)) {
        return s.substring(prefix.length());
    } else {
        return s;
    }
}
public static String chopSuffix(String s, String suffix) {
    if (s.endsWith(suffix)) {
        return s.substring(0, s.length() - suffix.length());
    } else {
        return s;
    }
}
public static String chopPresuffix(String s, String presuffix) {
    return chopSuffix(chopPrefix(s, presuffix), presuffix);
}

Then we can have:

    System.out.println(
        chopPrefix("abcdef", "abc")
    ); // def

    System.out.println(
        chopSuffix("abcdef", "ef")
    ); // abcd

    System.out.println(
        chopPresuffix("abcdef", "cd")
    ); // abcdef

    System.out.println(
        chopPresuffix("abracadabra", "abra")
    ); // cad
polygenelubricants