let SwiftString = "Hello" var emptyString = ""// empty string literal var anotherEmptyString = String()
字符和字符串
遍历字符串
1 2 3
forcharin SwiftString { print(char) }
通过 Character类型创建单个字符
1
let char : Character = "H"
String值可以通过传入 Character来构造:
1 2 3
let charArr : [Character] = ["H", "e", "l", "l", "o"] print(String(char)) // H print(String(charArr)) // Hello
拼接字符串
1 2 3 4 5
//方式一: let addString = String(charArr) + String(char) //HelloH //方式二: var addString2 = "Why" addString2 += String(charArr) //"WhyHello"
字符串个数
1 2 3
let count1 = SwiftString.count //5(类型: String.CharacterView.IndexDistance) let count2 = SwiftString.characters.count // 5(Int型) count1:
是否为空
1
let isStr = SwiftString.isEmpty //false
去掉某一个或几个字符
1 2 3 4 5 6
let text1 = SwiftString.dropFirst()//"ello" let text2 = SwiftString.dropLast()//"Hell" let text3 = SwiftString.dropFirst(2)//"llo" let text4 = SwiftString.dropLast(2)//"Hel" //注:以上皆为String.SubSequence类型 let text5 = String(text1) //"ello"---text5为String类型
倒叙
1
let text6 = String(SwiftString.reversed()) //"olleH"
字符串分割数组
1 2 3
let swiftString2 = "one two three" let StrArr = swiftString2.split(separator: " ") //["one", "two", "three"] //let StrArr: [String.SubSequence]
删除不符合ASCII编码的字符
1 2 3 4 5
let swiftString3 = "quanjun 🐷," let qj = swiftString3.filter { (char) -> Bool in returnchar.unicodeScalars.reduce(true, { $0 && $1.isASCII }) } print(qj) //"quanjun ,"
for item in array3 { print(item) } //元组输出 for (index, item) in array3.enumerated() { print("\(index)---\(item)") } //倒叙输出 for item in array3.reversed() { print(item) }
//forEach遍历,如同for-in let arr = [1, 9, 3, 3, 4, 5, 6, 5] arr.forEach { (x) in print(x) }