爪哇-分裂和修剪在一个镜头

我有一个这样的字符串: String attributes = " foo boo, faa baa, fii bii,"我想得到这样的结果:

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

所以我的问题是如何分割和修剪在一个镜头我已经分割:

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

spaces仍然在结果中:

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

我知道我们可以做一个循环,使 trim为每一个,但我想使它在镜头。

100270 次浏览

What about spliting with comma and space:

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

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

Using java 8 you can do it like this in one line

String[] result = Arrays.stream(attributes.split(",")).map(String::trim).toArray(String[]::new);

If there is no text between the commas, the following expression will not create empty elements:

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

previously posted here: https://blog.oio.de/2012/08/23/split-comma-separated-strings-in-java/

create your own custom function

private static String[] split_and_trim_in_one_shot(String string){
String[] result  = string.split(",");
int array_length = result.length;


for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;

Overload with a consideration for custom delimiter

private static String[] split_and_trim_in_one_shot(String string, String delimiter){
String[] result  = string.split(delimiter);
int array_length = result.length;


for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;

with streams

public static List<String> split(String str){
return Stream.of(str.split(","))
.map(String::trim)
.map (elem -> new String(elem))//optional
.collect(Collectors.toList());
// 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

Best way is:

value.split(",").map(function(x) {return x.trim()});

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.

ApaceCommons StringUtils.stripAll function can be used to trim individual elements of an array. It leaves the null as null if some of your array elements are null.

Here,

String[] array = StringUtils.stripAll(attributes.split(","));