Wednesday, 1 November 2017

String split behavior in Python/Scala/Java & AWK/Perl/Ruby

https://chriszetter.com/blog/2017/10/29/splitting-strings/

The crux part of the post is about what happens when we split an empty string with a delimiter.

In Python, "".split(",") returns [""]. The reason behind why this works this way is explained as:

"aa".split(",") returns ["aa"]
"a".split(",") returns ["a"]
so, "".split(",") returns [""]

This behavior is same for Java, Scala and other languages which are mentioned in the post.

But in Ruby, "".split(",") returns []. The reason why this works this way is because:

"aa,aa".split(",") returns ["aa","aa"]
"aa".split(",") returns ["aa"]
"".split(",") returns []

Ruby operates based on field concept which is inherited from AWK.

For more information please refer the link mentioned on the top of the post.