我想用空格作为分隔符来分割它们,但<>中的空格应该被忽略。
输出到"abc <def deaf;hello world> good"
应该是
- abc
-
<def deaf;hello world>
- 好
如何在 Java 中实现此功能? 正则表达式应该可以工作,但不使用正则表达式实现会更好。
最佳答案
最简单的方法是遍历字符串:
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));
您的 sample "abc <def deaf;hello world> good"
,结果是["abc", "<def deaf;hello world>", "good"]
关于java - 用空格作为分隔符将它们分开,但<>中的空格在Java中应该被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19481448/