swift字符串操作

/*

split(" ")按照" "分割字符串,对每个分割出来的字符创建为String

lazy是延迟调用

map(String.init) == map {String($0)}

后者必须使用{}是因为调用了参数$0

*/

let s = "1 2 3 4 5"

let s2 = s.characters.split(" ").lazy.map(String.init)

let s3 = s.characters.split(" ").map {String($0)}

s2.first

s3.first

let s4 = s.characters.split(s.lengthOfBytesUsingEncoding(NSUTF8StringEncoding), allowEmptySlices: true) { (char) -> Bool in

return char == " "

}.map(String.init)

s4.first

//字符串中替换字符

let ss = "1?2?3?"

let ss2 = ss.stringByReplacingOccurrencesOfString("?", withString: "/", options: .LiteralSearch, range: nil)

ss2

let sss = " 123 "

//字符串中过滤字符

let ss3 = sss.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

ss3

//将数组中元素拼接为字符串

let ssss = ["1", "2", "3"]

let ss4 = ssss.joinWithSeparator("/")

你可能感兴趣的:(swift字符串操作)