Java – Split and trim in one shot

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

  1. Java – Split and trim in one shot

    Use regular expression \s*,\s* for splitting.
    String result[] = attributes.split("\\s*,\\s*");

  2. 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*");
Advertisements

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);
Advertisements

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.

Advertisements

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

Advertisements

Original Author Naveen Of This Content

Conclusion

Advertisements

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment