0

我想用空格分隔它们,但 <> 中的空格应该被忽略。

的输出"abc <def deaf;hello world> good"应该是

  • 美国广播公司
  • <def deaf;hello world>
  • 好的

如何在 Java 中实现这一点?RegEx 应该可以工作,但没有 regEx 的实施会更好。

4

1 回答 1

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"]

于 2013-10-20T19:07:03.030 回答