Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Split and trim in one shot

Tags:

java

string

split

I have a String like this : String attributes = " foo boo, faa baa, fii bii," I want to get a result like this :

String[] result = {"foo boo", "faa baa", "fii bii"}; 

So my issue is how should to make split and trim in one shot i already split:

String[] result = attributes.split(","); 

But the spaces still in the result :

String[] result = {" foo boo", " faa baa", " fii bii"};                     ^           ^           ^ 

I know that we can make a loop and make trim for every one but I want to makes it in shot.

like image 388
YCF_L Avatar asked Jan 31 '17 09:01

YCF_L


People also ask

How do you use split and trim together?

Split and Trim String input = " car , jeep, scooter "; To remove extra spaces before and/or after the delimiter, we can perform split and trim using regex: String[] splitted = input. trim().

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

What does string's trim () method do in Java?

Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.

How do you do Ltrim and Rtrim in Java?

ltrim is then a substring starting at the first non-whitespace character. Or for R-Trim, we'll read our string from right to left until we run into a non-whitespace character: int i = s. length()-1; while (i >= 0 && Character.


1 Answers

Use regular expression \s*,\s* for splitting.

String result[] = attributes.split("\\s*,\\s*"); 

For Initial and Trailing Whitespaces
The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same:

String result[] = attributes.trim().split("\\s*,\\s*"); 
like image 182
Raman Sahasi Avatar answered Oct 04 '22 10:10

Raman Sahasi