Java - 一次拆分和修剪 [英] Java - Split and trim in one shot
问题描述
我有一个这样的字符串:String attributes = " foo boo, faa baa, fii bii,"
我想得到这样的结果:
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(",");
但是 spaces
仍然在结果中:
But the spaces
still in the result :
String[] result = {" foo boo", " faa baa", " fii bii"};
^ ^ ^
我知道我们可以制作一个循环并为每个人制作trim
,但我想在镜头中制作它.
I know that we can make a loop and make trim
for every one but I want to makes it in shot.
推荐答案
使用正则表达式 s*,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*");
这篇关于Java - 一次拆分和修剪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!