Swift学习笔记(4):字符串

目录:

  • 初始化
  • 常用方法或属性
  • 字符串索引

初始化

创建一个空字符串作为初始值:

var emptyString = ""                // 空字符串字面量
var anotherEmptyString = String()   // 初始化方法,两个字符串均为空并等价。
常用方法或属性
 1 var empty = emptyString.isEmpty    // 判断字符串是否为空
 2 var welcome = "string1" + string2  // 使用 + 或 += 拼接字符串
 3 welcome.append("character")        // 使用append()在字符串末尾追加字符
 4 
 5 // 使用 (变量) 进行字符串插值
 6 let multiplier = 3
 7 let message = "(multiplier) times 2.5 is (Double(multiplier) * 2.5)" 
 8 
 9 // 使用 == 或 != 进行字符串比较
10 if quotation == sameQuotation {
11     print("These two strings are considered equal")
12 }
13 
14 // 使用 hasPrefix() 和 hasSuffix() 判断是否又前缀或后缀
15 if scene.hasPrefix("Act 1 ") {
16     print("The string has the prefix of Act 1“)
17 }

注意:

・不能将一个字符串或者字符添加到一个已经存在的字符变量上,因为字符变量只能包含一个字符。
・插值字符串中写在括号中的表达式不能包含非转义反斜杠 (  ),并且不能包含回车或换行符。
字符串索引

可以通过字符串下标或索引属性和方法来访问和修改它,String.Index对应着字符串中的Character位置。

 1 sampleString.startIndex.         // 获取第一个字符的索引    
 2 sampleString.endIndex            // 获取最后一个字符的索引
 3 
 4 let greeting = "Guten Tag!"
 5 greeting[greeting.startIndex]    // G 使用下标获取字符
 6 greeting[greeting.index(before: greeting.endIndex)]   // !
 7 greeting[greeting.index(after: greeting.startIndex)]  // u
 8 
 9 let index = greeting.index(greeting.startIndex, offsetBy: 7)
10 greeting[index]                                       // a
11 
12 /* 
13     greeting[greeting.endIndex]        // error Index越界
14     greeting.index(after: endIndex)    // error Index越界
15 */
16 
17 // 使用 characters.indices 属性创建一个包含全部索引Range来遍历字符串中单个字符
18 for index in greeting.characters.indices {
19     print("(greeting[index]) ", terminator: "") // 输出 "G u t e n T a g ! "
20 }
21 
22 var welcome = "hello"
23 welcome.insert("!", at: welcome.endIndex)        // welcome 等于 "hello!"
24 welcome.remove(at: welcome.index(before: welcome.endIndex))// welcome 等于 "hello"

注意:

・可扩展的字符群集可以组成一个或者多个Unicode标量。这意味着不同的字符以及相同字符的不同表示方式可能需要不同数量的内存空间来存储。所以Swift中的字符在一个字符串中并不一定占用相同的内存空间。因此在没有获得字符串可扩展字符群集范围的时候,是不能计算出字符串的字符数量,此时就必须遍历字符串全部的 Unicode 标量,来确定字符数量。
声明:该系列内容均来自网络或电子书籍,只做学习总结!
原文地址:https://www.cnblogs.com/Youhei/p/6875241.html