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?
What is String in Java? Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.
The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1 if the second argument is given. Syntax : public String substring(int begIndex, int endIndex) Parameters : beginIndex : the begin index, inclusive. endIndex : the end index, exclusive.
Substring in Java is a commonly used method of java. lang. String class that is used to create smaller strings from the bigger one. As strings are immutable in Java, the original string remains as it is, and the method returns a new string.
In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. String greeting = "Hello world!"; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!
There's nothing built in, but Apache commons has the StringUtils class which has a suitable left function for you.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With