string常用的一些操作方式
//字符串 //1.初始化字符串 //1.1通过字面量赋值的方式初始化字符串 let tempStrig = "this is temp string"
let tempStrig = "this is TEMP string" //字母大小写 print(tempStrig.uppercased()) print(tempStrig.lowercased())
//1.2通过创建String实例化的方法初始化字符串 let anoutherString = String() //2.获取字符串长度 let string = "晚上去跑步,go" //2.1utf8 获取字节 let leng = string.lengthOfBytes(using: String.Encoding.utf8) print(leng) //2.2获取字符长度,大多数情况下这个 let leng2 = string.characters.count print(leng2) //2.3字符串遍历 for char in string.characters{ print(char) } //3 连接字符串和字符 //3.1加法赋值连接字符串 var varStr = "qq" varStr += ".com" print(varStr) //3.2 加法预算符连接字符串 let string1 = "Hello" let string2 = "World" var string3 = string1 + string2 print(string3) //追加字符 string3.append("!") //format 拼接字符串 let timeString = String(format:"%@,%d%@","现在",6,"点") print(timeString)
//字符串截取 let swiftString = "好喜欢!!!" //将swiftString 转换为OC 的字符串使用,根据范围来截取字符串 let subString1 = (swiftString as NSString).substring(with: NSMakeRange(1, 3)) print(subString1) //截取下标2 之前的字符 let subString2 = (swiftString as NSString).substring(to: 2) print(subString2) //截取下标2 之后(含有2) let subString3 = (swiftString as NSString).substring(from: 2) print(subString3) var insertStr = "明天星期天" //插入 //字符串最后 insertStr.insert("a", at: insertStr.endIndex) print(insertStr) //字符串最前 insertStr.insert("a", at: insertStr.startIndex) print(insertStr) //在指定位置插入 insertStr.insert("g", at: insertStr.index(before: insertStr.index(insertStr.startIndex, offsetBy: 3))) print(insertStr) //移除指定下标字符 insertStr.remove(at: insertStr.index(before: insertStr.index(insertStr.startIndex, offsetBy: 1))) print(insertStr) //系统提供的方法挺多的,大家有兴趣可以多看看
//字符串比较 //比较字符是否相同 let s1 = "好的" let s2 = "好的" if s1 == s2 { print("s1 == s2") }else{ print("s1 != s2") } let s3:NSString = "ok" let s4:NSString = "ok!" if s3.isEqual(to: s4 as String) { print("s3 == s4") }else{ print("s3 != s4") } //比较字符串的前缀,后缀 let array = ["do.docx","good.docx","name.docx","data.json","good.json"] for d in array { if d.hasPrefix("good"){ print("前缀为good:\(d)") } } for d in array { if d.hasSuffix(".json"){ print("后缀为.json:\(d)") } }