在字符集的任何字符上拆分字符串

时间:2016-01-23 19:58:19

标签: ios swift swift2

是否可以根据字符集中的字符获取字符串并进行拆分?

let sourceString = "This is the original string/sentence."

let nonAlphabet = NSCharacterSet(charactersInString: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").invertedSet

// let words = sourceString.split(charSet:nonAlphabet)

在这种情况下,单词= [“This”,“is”,“the”,“original”,“string”,“sentence”]

这可能吗?

2 个答案:

答案 0 :(得分:1)

if str(value) == '[[--]]': doSomething 有一个方法(NS)String

componentsSeparatedByCharactersInSet

由于句点,结果在数组的末尾会有一个空字符串。

答案 1 :(得分:-1)

let s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
let ss = "This is the original string/sentence."
let arr = ss.characters.split{!s.characters.contains($0)}.map{String($0)}
// ["This", "is", "the", "original", "string", "sentence"]