LoginSignup
15
12

More than 5 years have passed since last update.

プログラミング言語別 split の実験

Posted at

プログラミング言語別 split の実験

概要

ふと文字列の分割 (split) の挙動が気になったので手元のいくつかの言語で試してみました。
環境は Mac OS X 10.9.2 です。

実験

文字列の前後にセパレータがある場合、split が返す結果がどうなるのか実験です。
分割対象の文字列は ,hoge,fuga, で、セパレータは , として結果を見てみます。

Elixir

$ elixir --version
# Elixir 0.12.5
$ elixir -e "IO.inspect String.split(\",hoge,fuga,\", \",\")"
# ["", "hoge", "fuga", ""]

Node.js

$ node --version
# v0.10.26
$ node -p "',hoge,fuga,'.split(',')"
# [ '', 'hoge', 'fuga', '' ]

Perl

$ perl --version
# This is perl 5, version 16
$ perl -e "print join(',', split(',', ',hoge,fuga,'))"
# ,hoge,fuga

PHP

$ php --version
# PHP 5.4.24
$ php -r "print_r(split(',', ',hoge,fuga,'));"
# Array
# (
#     [0] =>
#     [1] => hoge
#     [2] => fuga
#     [3] =>
# )

Python

$ python --version
# Python 2.7.6
$ python -c "print ',hoge,fuga,'.split(',')"
# ['', 'hoge', 'fuga', '']

R

$ r --version
# R version 3.0.3 (2014-03-06) -- "Warm Puppy"
$ r -q -e "unlist(strsplit(',hoge,fuga,', ','))"
# [1] ""     "hoge" "fuga"

Ruby

$ ruby --version
# ruby 2.0.0p247
$ ruby -e "p ',hoge,fuga,'.split(',')"
# ["", "hoge", "fuga"]

結果発表

言語 結果
Elixir "", "hoge", "fuga", ""
Node.js "", "hoge", "fuga", ""
Perl "", "hoge", "fuga"
PHP "", "hoge", "fuga", ""
Python "", "hoge", "fuga", ""
R "", "hoge", "fuga"
Ruby "", "hoge", "fuga"

split が返す結果の最後に差が出ました。Perl, R, Ruby は空文字が無いという結果に。

みんな大好き ECMA-262 の場合、String.prototype.split を見ると、最後のセパレータにマッチする箇所から対象文字列の最後までも部分文字列として扱うため空文字が挿入される仕様のようです。(T = 切り出される文字列, S = 対象の文字列, p = セパレータの位置, s = 対象の文字列の文字数)

14. Let T be a String value equal to the substring of S consisting of the characters at positions p (inclusive) through s (exclusive).

最後の空文字が無い言語の仕様が気になります。

まとめ

split を使う場合は、セパレータが文字列の最後にあると言語によって挙動が違うよ、という微妙な知識が得られました。
今回実験しなかった言語のバージョンも誰かお願いします。

15
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
12