Question

If I have a String:

String neatish = getTheString(); // returns "...neat..."

I know that I can get rid of the first ellipsis using:

getTheString().substring(3);

But I'm wondering if there's a similar one-line method that takes the end off, based on length? Like:

getTheString().substring(3).truncate(3);

I don't want a character-specific method, ie. one that works only on ellipses.

While there's a substring() that accepts two parameters, it requires the altering String to be saved off to a variable first to determine the length. (Or, you can call getTheString() twice.)

I can certainly write one, but I'm wondering if there is a one-line method either in the standard java.lang package, or in Apache Commons-Lang, that will accomplish this.

I'm 50% curious, and 50% avoiding re-inventing the wheel.

Update: To avoid confusion, I do not want:

String neatish = getTheString();
neatish = neatish.substring(3)...;

I'm instead looking for the back-end version of substring(), and wondering why there isn't one.

Was it helpful?

Solution 2

You can use subStringBefore and subStringAfter from Commons:

StringUtils.subStringAfter(StringUtils.subStringBefore(getTheString(), "..."), "...");

EDIT based on length:

You need: StringUtils.html#substring(java.lang.String, int, int)

StringUtils.substring(getTheString(), 3, -3);

OTHER TIPS

Fun exercise

String theString = new StringBuilder(getTheString()).delete(0, 3).reverse().delete(0, 3).reverse().toString();

Get the String into a StringBuilder, remove the first 3 chars, reverse it, remove the last 3 chars (which are now at the start), reverse it again.

getTheString().substring(3).replaceFirst("(?s)...$", "");
getTheString().replaceFirst("(?s)^...(.*)...$", "$1");

This removes the last 3 chars by a regular expression, where (?s) make . also match newlines. Use \\. to match a period. UGLY.

You could write a method to do it.

public static String trimChar(String s, char ch) {
    int start = 0;
    for(; start < s.length(); start++)
         if (s.charAt(start) != ch)
             break;
    int end = s.length();
    for(; end > start; end--)
         if (s.charAt(end-1) != ch)
             break;
    return s.substring(start, end);
}


String s = trimChar(getTheString(), '.');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top