首页 Swift中的字符串和字符
文章
取消

Swift中的字符串和字符

字符串基础

Swift 的 String类型是一种值类型。如果你创建了一个新的 String值, String值在传递给方法或者函数的时候会被复制过去,还有赋值给常量或者变量的时候也是一样。每一次赋值和传递,现存的 String值都会被复制一次,传递走的是拷贝而不是原本。

Swift 的默认拷贝 String行为保证了当一个方法或者函数传给你一个 String值,你就绝对拥有了这个 String值,无需关心它从哪里来。你可以确定你传走的这个字符串除了你自己就不会有别人改变它。

Swift 编译器优化了字符串使用的资源,实际上拷贝只会在确实需要的时候才进行。这意味着当你把字符串当做值类型来操作的时候总是能够有用很棒的性能。

初始化一个空字符串

1
2
var emptyString = ""
var anotherEmptyString = String()

检查字符串是否为空:

1
2
3
if emptyString.isEmpty {
    print("Nothing to see here")
}

字面量

在Swift中,可以使用双引号(”)来表示一个字符串字面量。例如:

1
let hello = "Hello, world!"

字符串字面量里的特殊字符

字符串字面量能包含以下特殊字符:

  • 转义特殊字符 \0 (空字符), \ (反斜杠), \t (水平制表符), \n (换行符), \r(回车符), " (双引号) 以及 ' (单引号);
  • 任意的 Unicode 标量,写作 \u{n},里边的 n是一个 1-8 个与合法 Unicode 码位相等的16进制数字。

字符串变量

我们可以用var关键字定义一个可变字符串变量,也可以用let关键字定义一个不可变字符串常量。例如:

1
2
3
4
5
var greeting = "Hello"
let name = "John"

greeting += ", " + name // 将greeting改为"Hello, John"
name += " Doe" // 编译错误:常量不能修改

字符串插值

我们可以使用字符串插值来将常量、变量、字面量和表达式转换为字符串中的占位符。在字符串字面量中,将占位符放入括号中,并以反斜杠(\)作为前缀。例如:

1
2
let age = 20
let message = "I am \(age) years old."

字符串连接

字符串连接可以通过加号(+)运算符实现。 也可以使用加赋值符号( +=)在已经存在的 String值末尾追加一个 String值。 也可以使用String类型的 append()方法来可以给一个 String变量的末尾追加 Character值。 例如:

1
2
3
4
5
6
7
8
9
let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName

var instruction = "look over"
instruction += fullName

let exclamationMark: Character = "!"
fullName.append(exclamationMark)

多行字符串

多行字符串由一对三个双引号(””“)包裹而成,支持跨越多行的文本内容,并保留了所有的特殊字符和空白符。例如:

1
2
3
4
5
6
7
8
9
10
11
12
let multilineString = """
    This is a multi-line string.
    It can contain multiple lines of text.
    """

print(multilineString)


/*输出结果:

This is a multi-line string.
It can contain multiple lines of text.*/

字符

在Swift中,字符使用双引号(”)表示。例如:

1
let character: Character = "A"

字符串操作

计算字符串长度

我们可以使用 count 属性来计算字符串中字符的数量。例如:

1
2
let str = "Hello, world!"
let length = str.count // length 值为 13

字符串比较

Swift提供了三种方式进行字符串比较:

  1. 使用等于运算符(==)进行比较。
  2. 使用hasPrefix(_:)方法检查字符串是否以指定的前缀开头。
  3. 使用hasSuffix(_:)方法检查字符串是否以指定的后缀结尾。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let str1 = "Hello, world!"
let str2 = "hello, world!"

if str1 == str2 {
    print("The two strings are equal.")
} else {
    print("The two strings are not equal.")
}

if str1.hasPrefix("Hello") {
    print("The string starts with 'Hello'.")
}

if str1.hasSuffix("world!") {
    print("The string ends with 'world!'.")
}


/*输出结果:

The two strings are not equal.
The string starts with 'Hello'.
The string ends with 'world!’.*/

字符串分割

我们可以使用 split(separator:maxSplits:omittingEmptySubsequences:) 方法将字符串分割成子字符串数组。其中,separator 参数表示要分割的分隔符;maxSplits 参数表示最大分割次数;omittingEmptySubsequences 参数表示是否省略空的子字符串。例如:

1
2
3
4
5
6
7
8
9
10
11
12
let csv = "apple,banana,orange"
let items = csv.split(separator: ",")

for item in items {
    print(item)
}

/*输出结果:

apple
banana
orange*/

字符串替换

我们可以使用 replacingOccurrences(of:with:options:range:) 方法将字符串中的某个子字符串替换为另一个字符串。其中,of 参数表示要替换的子字符串;with 参数表示替换后的新字符串;options 参数表示匹配选项;range 参数表示要替换的子字符串范围。例如:

1
2
3
4
let str = "Hello, world!"
let replaced = str.replacingOccurrences(of: "world", with: "Swift")

print(replaced) // 输出结果为 "Hello, Swift!"

字符串大小写转换

我们可以使用 uppercased()lowercased() 方法将字符串转换为大写或小写。例如:

1
2
3
4
5
6
7
let str = "Hello, world!"

let uppercase = str.uppercased()
let lowercase = str.lowercased()

print(uppercase) // 输出结果为 "HELLO, WORLD!"
print(lowercase) // 输出结果为 "hello, world!"

Unicode

Unicode 标量

Unicode是一种字符集,用于表示世界上所有的字符。在Swift中,每个字符都是由一个或多个Unicode标量组成的。

Unicode 编码

每个Unicode标量都有一个唯一的编号,称为Unicode编码点。我们可以使用\u{}语法来表示一个Unicode标量的编码点,其中{}内为16进制数。例如:

1
2
let heart = "\u{1F496}"
print(heart) // 输出结果为 "💖"

字符串索引

我们可以使用字符串的索引来访问其中的字符。在Swift中,每个字符都由一个或多个Unicode标量组成,因此字符串的索引既可以是整数,也可以是对应的Unicode标量。例如:

1
2
3
4
5
let str = "Hello, world!"
let index = str.index(str.startIndex, offsetBy: 7)

let character = str[index]
print(character) // 输出结果为 "w"

遍历字符串

我们可以使用for-in循环遍历字符串中的每个字符。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let str = "Hello, world!"

for character in str {
    print(character)
}

/*输出结果:

H
e
l
l
o
,
 
w
o
r
l
d
!
*/
本文由作者按照 CC BY 4.0 进行授权

Swift中的运算符

Swift中的集合类型