• 「MacOS」Swift 第三章:字符串和字符


    3 字符串和字符

    字符串和字符分别使用 String 类和 Character 类表示,字符串是一系列字符的集合。

    字符串之间的拼接使用+号完成;也可向可变字符串中插入常量、变量、字面量,这一过程称为字符串插值。

    3.1 字符串字面量

    字符串字面量是由一对双引号包裹着的具有固定顺序的字符集。字符串字面量允许为单行或多行。多行字符串字面量可以跨多行书写。单行使用一对双引号指明,多行使用一对三引号指明。例如:

    // 单行字符串
    let someString = "Some string literal value"
    
    // 多行字符串,此时字面量中包含换行符
    let quotation = """
    The White Rabbit put on his spectacles.  "Where shall I begin,
    please your Majesty?" he asked.
    
    "Begin at the beginning," the King said gravely, "and go on
    till you come to the end; then stop."
    """
    
    // 多行字符串,此时字面量中使用反斜杠(\)隐去换行符,实际打印出来是一串不带换行符的字符串
    let softWrappedQuotation = """
    The White Rabbit put on his spectacles.  "Where shall I begin, \
    please your Majesty?" he asked.
    
    "Begin at the beginning," the King said gravely, "and go on \
    till you come to the end; then stop."
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    3.2 字符串字面量中的特殊字符

    什么是转义字符

    在了解什么是转义字符后,那么swift中的转义字符包括:

    • \0 空字符
    • \\ 反斜杠符
    • \t 水平制表符
    • \n 换行符
    • \r 回车符
    • " 双引号
    • ’ 单引号

    此外swift中还包括了Unicode标量,用法为\u{n},其中u是小写,n是整数。该标量对应各种特殊字符。

    转义字符和Unicode标量用法如下:

    let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
    // "Imagination is more important than knowledge" - Einstein
    let dollarSign = "\u{24}"             // $,Unicode 标量 U+0024
    let blackHeart = "\u{2665}"           // ♥,Unicode 标量 U+2665
    let sparklingHeart = "\u{1F496}"      // 💖,Unicode 标量 U+1F496
    
    • 1
    • 2
    • 3
    • 4
    • 5

    此外,在三引号字符串中可以直接使用双引号,但使用三引号需要加\

    3.3 初始化字符串

    初始化方法包括:

    var emptyString = ""               // 空字符串字面量
    var anotherEmptyString = String()  // 初始化方法
    // 两个字符串均为空并等价。
    
    • 1
    • 2
    • 3

    空字符串检查,通过调用字符串方法 isEmpty :

    if emptyString.isEmpty {
        print("Nothing to see here")
    }
    // 打印输出:“Nothing to see here”
    
    • 1
    • 2
    • 3
    • 4

    字符串可以使用 + 进行字符串之间相加。

    3.4 字符串是值类型

    值类型的意思是,在传递字符串到函数、方法中时,原始字符串不会被改变,改变的是函数/方法中从原字符串中拷贝的字符串副本。

    3.5 使用字符、字符串

    字符串支持遍历,也就意味着可以循环:

    for character in "Dog!🐶" {
        print(character)
    }
    // D
    // o
    // g
    // !
    // 🐶
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    可以通过指明变量类型来声明字符:

    let exclamationMark: Character = "!"
    
    • 1

    可以通过传递字符类型创建字符数组:

    let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
    let catString = String(catCharacters)
    print(catString)
    // 打印输出:“Cat!🐱”
    
    • 1
    • 2
    • 3
    • 4

    3.6 连接字符串和字符

    字符串可以通过+连接,也可以使用append方法将一次字符添加到字符串尾部:

    let string1 = "hello"
    let string2 = " there"
    var welcome = string1 + string2
    // welcome 现在等于 "hello there"
    
    let exclamationMark: Character = "!"
    welcome.append(exclamationMark)
    // welcome 现在等于 "hello there!"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    一个神奇的输出(其实这一章文档有讲,但我没做笔记,当时也没懂什么意思,但现在懂了):

    let badStart = """
    one
    two
    """
    let end = """
    three
    """
    print(badStart + end)
    // 打印两行:
    // one
    // twothree
    
    let goodStart = """
    one
    two
    
    """
    print(goodStart + end)
    // 打印三行:
    // one
    // two
    // three
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    3.7 字符串插值

    字符串插值是一种构建新字符串的方式,单行和多行字符串都可以使用字符串插值,插入格式为\(要插入的字符)

    let multiplier = 3
    let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
    // message 是 "3 times 2.5 is 7.5"
    
    • 1
    • 2
    • 3

    如果要输出插值变量本身的名称,则可以:

    print(#"Write an interpolated string in Swift using \(multiplier)."#)
    // 打印 "Write an interpolated string in Swift using \(multiplier)."
    
    • 1
    • 2

    在使用扩展字符串分隔符的字符串中使用字符串插值,需要这样写:

    print(#"6 times 7 is \#(6 * 7)."#)
    // 打印 "6 times 7 is 42."
    
    • 1
    • 2

    3.8 Unicode

    Unicode是一个用于在不同书写系统中对文本进行编码、表示和处理的国际标准,它可以用标准格式表示来自任意语言几乎所有的字符,并能够对文本文件或网页这样的外部资源中的字符进行读写操作。swift的字符串String和字符Character完全兼容Unicode标准。

    。。。这一块懒记了,跳过

    3.9 计算字符数量

    获取字符串中字符数量,可以调用count方法:

    let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
    print("unusualMenagerie has \(unusualMenagerie.count) characters")
    // 打印输出“unusualMenagerie has 40 characters”
    
    • 1
    • 2
    • 3

    3.10 访问和修改字符串

    字符串有一个index方法来索引字符串中的每一个字符,而不同的字符占有的内存空间也不同,因此索引字符串必须从String开头遍历每一个Unicode标量直到结尾,因此String不能使用整数做索引。

    字符串还包括startIndex索引和endIndex索引方法,前者会返回字符串第一个字符的索引,后者返回字符串尾部的索引,代表字符串结尾,而不是最后一个字符的索引。

    使用索引需要通过字符串Index方法,该方法包括一个index(before:)方法和index(after:)方法,前者返回索引位置前一个位置的字符,后者返回索引位置后一位字符。还可以通过index(_:offsetBy:)方法来获取当前索引为起始偏移偏移量位置的字符。

    越位索引会直接报错

    let greeting = "Guten Tag!"
    greeting[greeting.startIndex]
    // G
    greeting[greeting.endIndex]
    // error报错,因为endIndex不代表字符串最后一个字符
    greeting[greeting.index(before: greeting.endIndex)]
    // !
    greeting[greeting.index(after: greeting.startIndex)]
    // u
    let index = greeting.index(greeting.startIndex, offsetBy: 7)
    greeting[index]
    // a
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    如果字符串为空,则startIndex和endIndex等价。

    使用 `indices``属性会创建一个包含全部索引的范围:

    for index in greeting.indices {
       print("\(greeting[index]) ", terminator: "")
    }
    // 打印输出“G u t e n   T a g ! ”
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    PDF处理技巧分享之PDF合并:一键实现几个PDF合并成一个PDF
    easyexcel行数超过500行,randomAccessWindowSize滑动窗口优化带来的”问题“
    几种能让Mac“飞”起来的系统空间清理方法
    JQ语法 选择器 事件
    【云上探索实验室】编程范式变革进行时——CodeWhisperer实践全流程及测评分析报告
    【即将开源】⽤于3D激光雷达SLAM闭环检测的词袋模型BoW3D
    【排序】十大排序算法
    iconfont 的symbol字体如何修改颜色 / svg如何修改颜色?
    Docker设置开机自启动
    docker save & docker export 区别
  • 原文地址:https://blog.csdn.net/Liiipseoroinis/article/details/127984708