LoginSignup
6

More than 5 years have passed since last update.

posted at

Swiftの文字分割におけるsplit(separator:)とcomponents(separatedBy:)の違い

前書き

文字分割なんて同じだろ、と高を括っていたらそーじゃなかった。

split(separator:)の場合

splitの場合
let str = "ABCDEFGFEDCBA"
let retVal = str.split(separator: "A")
print(retVal)
結果
["BCDEFGFEDCB"]

components(separatedBy:)の場合

splitの場合
let str = "ABCDEFGFEDCBA"
let retVal = str.components(separatedBy: "A")
print(retVal)
結果
["", "BCDEFGFEDCB", ""]

結論

先頭、末尾にseparatorがあった場合…

  • split(separator:)は、削ぎ落とそされる。
  • components(separatedBy:)は、「空文字」との分割が為される。

あとがき

JavaScriptのsplit()とは挙動が違うので注意。
文字列置換処理を

str.split(separator: "A").joined(separator: "B")

とか書くと先頭や末尾が削ぎ落とされてバグる。

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
What you can do with signing up
6