我想用空格作为分隔符拆分它们,但是<>中的空格应该被忽略。
"abc <def deaf;hello world> good"
的输出应为
<def deaf;hello world>
如何在Java中实现它? RegEx应该可以工作,但是没有regEx的实现会更好。
答案 0 :(得分:3)
最简单的方法是走绳子:
ArrayList<String> out = new ArrayList<String>();
int i, last = 0;
int depth = 0;
for(i=0; i != string.length(); ++i) {
if(string.charAt(i) == '<') ++depth;
else if(string.charAt(i) == '>') { if(depth >0) --depth; }
else if(string.charAt(i) == ' ' && depth == 0) {
out.add(string.substring(last, i));
last = i+1;
}
}
if(last < string.length()) out.add(string.substring(last));
对于您的样本"abc <def deaf;hello world> good"
,结果为["abc", "<def deaf;hello world>", "good"]