字符串在编程中是形影不离的,懂多点,用起来就方便点。
下面有字符串常用的一系列操作
替换 - 过滤 - 切割 - 拼接
var str = " 🚗 🍎 🚗 🍎 "
//字符串替换操作 -> 把苹果都换成汽车
let filtered = str.stringByReplacingOccurrencesOfString("🍎", withString: "🚗", options: .LiteralSearch, range: nil)
// = " 🚗 🚗 🚗 🚗 "
//过滤也也一样 -> 比如去掉字符串的所有空格
let filtered2 = str.stringByReplacingOccurrencesOfString(" ", withString: "", options: .LiteralSearch, range: nil)
// = "🍎🚗🍎🚗"
//去掉开头和结尾的空白
let newStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// = " 🚗 🍎 🚗 🍎"
//切割 -> 返回数组
let splitedArr1 = str.componentsSeparatedByString(" ")
// = ["", "", "🚗", "🍎", "🚗", "🍎", ""]
let splitedArr2 = str.characters.split{ $0 == " "}.map(String.init)
// = ["🚗", "🍎", "🚗", "🍎"]
//拼接 数组 -> 字符串
let strGG = ["1","2","3"].joinWithSeparator("-")
// = "1-2-3"
let str = ["2","3","4"].reduce("", combine: +) // = "234"
更多字符串基础操作内容可以看哥这篇 Swift - String 初级用法合集