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

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

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?


Answer 1:

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

Answer 2:

If you don’t want to add the StringUtils Library you can still use it the way you want like so:

String string = (string.lastIndexOf(",") > -1 )?string.substring(0, string.lastIndexOf(",")): string;

Answer 3:

No there is not left() in the String class, as you can refer API. But as @Mark said Apache StringUtils has several methods: leftPad(), rightPad(), center() and repeat(). You can also check

Answer 4:

put the below function in a class:

 public static String getLeftString(String st,int length){
    int stringlength=st.length();

        return st;

    return st.substring((stringlength-length));