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.
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().
Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.
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.
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*");
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