返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #52895同步于 2016/9/13
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
求问java split()用法,我有个地方比较疑惑
nijian81
2016/9/13镜像同步18 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
【 在 wkc0330 的大作中提到: 】
: 你把空格都换成逗号,是不是就比较好理解了,
: 例如:a,,,b
: 按逗号split,出来的应该是
: ...................
我现在大概明白split如何工作了,像我的图中画的
但是有个问题,system.out.println(....),为什么开头的那个空格省略了?
【 在 dss886 的大作中提到: 】
: 一个空格切一次,连续的空格切出来的中间的String就是一个空字符串
: 你用debug直接看b[]的内容就很清楚了
嗯嗯,现在明白了
你这是按什么分隔的?把代码贴出来瞅瞅
【 在 nijian81 的大作中提到: 】
:
: [upload=1][/upload]
: 我现在大概明白split如何工作了,像我的图中画的
: ...................
```
public String[] split(String regex, int limit) {
/* fastpath if the regex is a
(1)one-char String and this character is not one of the
RegEx's meta characters ".$|()[{^?*+\\", or
(2)two-char String and the first char is the backslash and
the second is not the ascii digit or ascii letter.
*/
char ch = 0;
if (((regex.value.length == 1 &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 &&
regex.charAt(0) == '\\' &&
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
int off = 0;
int next = 0;
boolean limited = limit > 0;
ArrayList<String> list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
//assert (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
break;
}
}
// If no match was found, return this
if (off == 0)
return new String[]{this};
// Add remaining segment
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
// Construct result
int resultSize = list.size();
if (limit == 0) {
while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
resultSize--;
}
}
String[] result = new String[resultSize];
return list.subList(0, resultSize).toArray(result);
}
return Pattern.compile(regex).split(this, limit);
}
```