[SOLVED] Is there a left()-function for Java strings?

Issue

I have an string str of unknown length (but not null) and a given maximum length len, this has to fit in. All I want to do, is to cut the string at len.

I know that I can use

str.substring(0, Math.min(len, str.length()));

but this does not come handy, if I try to write stacked code like this

code = str.replace(" ", "").left(len)

I know that I can write my own function but I would prefer an existing solution. Is there an existing left()-function in Java?

Solution

There’s nothing built in, but Apache commons has the StringUtils class which has a suitable left function for you.

Answered By – Mark Chorley

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *