LoginSignup
1
4

More than 5 years have passed since last update.

Swift文字列分割で空文字列を除く

Posted at

Swift3で文字列をseparatorでsplitするには、以下の2つがありますが、結果は異なります。

"a,,b".components(separatedBy: ",")
// => ["a", "", "b"]

"a,,b".characters.split(separator: ",").map(String.init)
// => ["a", "b"]

特に、空文字列自体をsplitして空配列を期待しがちなので、注意。

"".components(separatedBy: ",")
//=> [""]

split関数は、引数で制御可能。

"a,,b".characters.split(separator: ",", maxSplits: 1, omittingEmptySubsequences: false).map(String.init)
// => ["a", ",b"]

結論: split関数を使う。

1
4
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
1
4