下面是一个示例字符串,我打算将它拆分为一个数组:
Hello My Name Is The Mighty Llama产出应是:
Hello My
Name Is
The Mighty
Llama下面的每一个空间都是分裂的,我怎么能在其他的空间上分开呢?
String[] stringArray = string.split("\\s");发布于 2013-12-06 16:55:04
你可以这样做:
String[] stringArray = string.split("(?<!\\G\\S+)\\s");发布于 2013-12-06 17:13:18
虽然这可以像this one那样使用拆分来解决,但我强烈建议在Pattern和Matcher类中使用更具可读性的方法。下面是解决这个问题的一个例子:
String string="Hello My Name Is The Mighty Llama";
Pattern p = Pattern.compile("\\S+(\\s\\S+)?");
Matcher m = p.matcher(string);
while (m.find())
System.out.println(m.group());产出:
Hello My
Name Is
The Mighty
Llamahttps://stackoverflow.com/questions/20429277
复制相似问题