Java, Scala, .NET, Lisp, Python, IDE's, Hibernate, MATLAB, Mathematica, Physics & Other

суббота, 29 августа 2009 г.

Что делает функцию разделения строки split в джаве такой "уникальной"

Казалось бы, функция split разделения строки на части по заданному разделителю, что в ней может быть такого особенного. Ну делит и делит себе, все отлично..

Посмотрим на пример написанный на Python:

s = ',1,,2,,'
tokens = s.split(',')
print('start')
for token in tokens:
print(token)
print('end')
_Winnie Colorizer


Выполняем.. вывод:
start

1

2


end

Все четко и предсказуемо. На стыке разделителей считается что находится пустая строка.

Теперь посмотрим пример на C#:

String[] tokens = ",1,,2,,".Split(new []{','});
Console.WriteLine("start");
for (int i = 0; i < tokens.Length; ++i )
{
Console.WriteLine(tokens[i]);
}
Console.WriteLine("end");
_Winnie Colorizer


Вывод аналогичен:
start

1

2


end

Ок, значит если я сейчас напишу код на java

String[] tokens = ",1,,2,,".split(",");
System.out.println("start");
for (int i = 0; i < tokens.length; ++i)
{
System.out.println(tokens[i]);
}
System.out.println("end");
_Winnie Colorizer


то можно с полной уверенность ожидать что вывод будет точно таким же. Ага.. Как же - черта с два!

start

1

2
end

Вот таким образом. Стоящие подряд разделители в конце строки почему-то полностью игнорируются.
Джавадок говорит следующее:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Опять не понятно - с чего вдруг "empty strings are therefore not included in the resulting array". Ситуацию проясняет только джавадок к методу:
public String[] split(String regex, int limit)

...
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
...

Как жаль. А мне было сначала показалось что я нашел багу.. Оказалось просто такая вот дурацкая особенность, которую надо иметь в виду.

Комментариев нет:

Отправить комментарий

Постоянные читатели