字符串是值类型
传递或赋值的是该NSString实例的一个引用,除非您特别要求进行值拷贝,否则字符串不会生成新的副本来进行赋值操作。
很明显无论该值来自于哪里,都是独自拥有的,字符串本身不会被更改。
在实际编译时,Swift 编译器会优化字符串的使用,使实际的复制只发生在绝对必要的情况下,这意味着将字符串作为值类型的同时可以获得极高的性能。
在实际编译时,Swift 编译器会优化字符串的使用,使实际的复制只发生在绝对必要的情况下,这意味着将字符串作为值类型的同时可以获得极高的性能。
计算字符数量
let str = "hello world,hello swift" print(str.characters.count)
比较字符串
let quotation = "我们是一样一样滴." let sameQuotation = "我们是一样一样滴." if quotation == sameQuotation { print("这两个字符串被认为是相同的") }
字符串字面值相同则认为字符串相等。
前缀或后缀相等
let romeoAndJuliet = [ "Act 1 Scene 1: Verona,A public place","Act 1 Scene 2: Capulet's mansion","Act 1 Scene 3: A room in Capulet's mansion","Act 1 Scene 4: A street outside Capulet's mansion","Act 1 Scene 5: The Great Hall in Capulet's mansion","Act 2 Scene 1: Outside Capulet's mansion","Act 2 Scene 2: Capulet's orchard","Act 2 Scene 3: Outside Friar Lawrence's cell","Act 2 Scene 4: A street in Verona","Act 2 Scene 5: Capulet's mansion","Act 2 Scene 6: Friar Lawrence's cell" ] var act1SceneCount = 0 for scene in romeoAndJuliet { if scene.hasPrefix("Act 1 ") { ++act1SceneCount } } print("There are \(act1SceneCount) scenes in Act 1") // 打印输出:"There are 5 scenes in Act 1" var mansionCount = 0 var cellCount = 0 for scene in romeoAndJuliet { if scene.hasSuffix("Capulet's mansion") { ++mansionCount } else if scene.hasSuffix("Friar Lawrence's cell") { ++cellCount } } print("\(mansionCount) mansion scenes; \(cellCount) cell scenes") // 打印输出:"6 mansion scenes; 2 cell scenes"
大小写字符串
let normal = "Could you help me,please?" let shouty = normal.uppercaseString // shouty 值为 "COULD YOU HELP ME,PLEASE?" let whispered = normal.lowercaseString // whispered 值为 "could you help me,please?"