「Swift」 split() メソッドで文字列を分割して配列を取得する

書式
文字列.split(separator: " “)
文字列の split() メソッドは Substring 型の配列を返します。
文字列.components(separatedBy: " “)
NSString の components() メソッドを使って、分割された String の配列を取得します。
components() メソッドの引数は、separatedBy のみなので、分割の結果、空文字列の要素があれば、配列に含まれます。

使用例

import Foundation

let target = "東京 品川区 新宿区 渋谷区 # "

let spResA = target.split(separator: " ")
let spResB = target.components(separatedBy: " ")

print("splitメソッドで文字列を分割する結果")
print(spResA)
print(type(of: spResA))
print(" componentsメソッドで文字列を分割する結果")
print(spResB)
print(type(of: spResB))

実行結果
$ swift 101.swift
splitメソッドで文字列を分割する結果
[“東京", “品川区", “新宿区", “渋谷区 #"]
Array<Substring>
componentsメソッドで文字列を分割する結果
[“東京", “品川区", “新宿区", “渋谷区 #", “"]
Array<String>

Swift

Posted by arkgame