gpt4 book ai didi

java - 用空格作为分隔符将它们分开,但<>中的空格在Java中应该被忽略

转载 作者:行者123 更新时间:2023-12-01 23:29:58 26 4
gpt4 key购买 nike

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

输出到"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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com