Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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?

like image 563
Alois Heimer Avatar asked Jun 26 '13 10:06

Alois Heimer


People also ask

What does string () do 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.

How do you slice a string in Java?

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.

How does substring () inside string works?

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.

How do you handle a string in Java?

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!


2 Answers

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

like image 152
Mark Chorley Avatar answered Nov 06 '22 18:11

Mark Chorley


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;
like image 39
BBaker Avatar answered Nov 06 '22 19:11

BBaker