Java-一键拆分和修剪 [英] Java - Split and trim in one shot
问题描述
我有一个像这样的字符串: String properties ="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(",");
但是空格
仍在结果中:
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屋!