swift2 字符与字符串

前端之家收集整理的这篇文章主要介绍了swift2 字符与字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

字符串是值类型


与NSString不同,创建了一个NSString实例,并将其传递给一个函数/方法,或者赋值给一个变量。

传递或赋值的是该NSString实例的一个引用,除非您特别要求进行值拷贝,否则字符串不会生成新的副本来进行赋值操作。

Swift 默认字符串拷贝的方式保证了在函数/方法中传递的是字符串的值。

很明显无论该值来自于哪里,都是独自拥有的,字符串本身不会被更改。

在实际编译时,Swift 编译器会优化字符串的使用,使实际的复制只发生在绝对必要的情况下,这意味着将字符串作为值类型的同时可以获得极高的性能



计算字符数量


  1. let str = "hello world,hello swift"
  2. print(str.characters.count)



比较字符串


  1. let quotation = "我们是一样一样滴."
  2. let sameQuotation = "我们是一样一样滴."
  3. if quotation == sameQuotation {
  4. print("这两个字符串被认为是相同的")
  5. }

字符串字面值相同则认为字符串相等。




前缀或后缀相等


  1. let romeoAndJuliet = [
  2. "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"
  3. ]
  4. var act1SceneCount = 0
  5. for scene in romeoAndJuliet {
  6. if scene.hasPrefix("Act 1 ") {
  7. ++act1SceneCount
  8. }
  9. }
  10. print("There are \(act1SceneCount) scenes in Act 1")
  11. // 打印输出:"There are 5 scenes in Act 1"
  12.  
  13. var mansionCount = 0
  14. var cellCount = 0
  15. for scene in romeoAndJuliet {
  16. if scene.hasSuffix("Capulet's mansion") {
  17. ++mansionCount
  18. } else if scene.hasSuffix("Friar Lawrence's cell") {
  19. ++cellCount
  20. }
  21. }
  22. print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
  23. // 打印输出:"6 mansion scenes; 2 cell scenes"



大小写字符串


  1. let normal = "Could you help me,please?"
  2. let shouty = normal.uppercaseString
  3. // shouty 值为 "COULD YOU HELP ME,PLEASE?"
  4. let whispered = normal.lowercaseString
  5. // whispered 值为 "could you help me,please?"

猜你在找的Swift相关文章