Trim characters in Java

2020-01-24 12:55发布

How can I trim characters in Java?
e.g.

String j = “\joe\jill\”.Trim(new char[] {“\”});

j should be

"joe\jill"

String j = “jack\joe\jill\”.Trim("jack");

j should be

"\joe\jill\"

etc

标签: java string trim
13条回答
你好瞎i
2楼-- · 2020-01-24 13:40

I would actually write my own little function that does the trick by using plain old char access:

public static String trimBackslash( String str )
{
    int len, left, right;
    return str == null || ( len = str.length() ) == 0 
                           || ( ( left = str.charAt( 0 ) == '\\' ? 1 : 0 ) |
           ( right = len > left && str.charAt( len - 1 ) == '\\' ? 1 : 0 ) ) == 0
        ? str : str.substring( left, len - right );
}

This behaves similar to what String.trim() does, only that it works with '\' instead of space.

Here is one alternative that works and actually uses trim(). ;) Althogh it's not very efficient it will probably beat all regexp based approaches performance wise.

String j = “\joe\jill\”;
j = j.replace( '\\', '\f' ).trim().replace( '\f', '\\' );
查看更多
登录 后发表回答