We Are Going To Discuss About Java – Split and trim in one shot. So lets Start this Java Article.
Java – Split and trim in one shot
- Java – Split and trim in one shot
Use regular expression
\s*,\s*
for splitting.String result[] = attributes.split("\\s*,\\s*");
- Java – Split and trim in one shot
Use regular expression
\s*,\s*
for splitting.String result[] = attributes.split("\\s*,\\s*");
Solution 1
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*");
Original Author Raman Sahasi Of This Content
Solution 2
Using java 8 you can do it like this in one line
String[] result = Arrays.stream(attributes.split(",")).map(String::trim).toArray(String[]::new);
Original Author Andrei Olar Of This Content
Solution 3
You can do it with Google Guava library this way :
List<String> results = Splitter.on(",").trimResults().splitToList(attributes);
which I find quite elegant as the code is very explicit in what it does when you read it.
Original Author Olivier Masseau Of This Content
Solution 4
// given input
String attributes = " foo boo, faa baa, fii bii,";
// desired output
String[] result = {"foo boo", "faa baa", "fii bii"};
This should work:
String[] s = attributes.trim().split("[,]");
As answered by @Raman Sahasi:
before you split your string, you can trim the trailing and leading spaces. I’ve used the delimiter
,
as it was your only delimiter in your string
Original Author Naveen Of This Content
Conclusion
So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.