0%

Swift字符串操作

字符串字面量

字符串字面量可以用于为常量和变量提供初始值:

1
2
let someString = "Some string const value"
var someString2 = "Some string varible value"

多行字符串字面量

如果你需要一个字符串是跨越多行的,那就使用多行字符串字面量 — 由一对三个双引号包裹着的具有固定顺序的文本字符集:

1
2
3
4
5
6
7
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."
"""

初始化空字符串

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

字符串判空

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

字符串可变性

1
2
3
4
5
6
7
var variableString = "Horse"
variableString += " and carriage"
// variableString 现在为 "Horse and carriage"

let constantString = "Highlander"
constantString += " and another Highlander"
// 这报告一个编译错误(compile-time error) - 常量字符串不可以被修改

遍历字符串中的字符

方法1:通过for in遍历字符串中全部的字符

1
2
3
for character in "ABCDE" {
print(character)
}

方法2:使用 indices 属性会创建一个包含全部索引的范围(Range),用来在一个字符串中访问单个字符。

1
2
3
4
5
let greeting = "Helo, World!"
for index in greeting.indices {
print("\(greeting[index]) ", terminator: "")
}
// 控制台输出:H e l o , W o r l d !

通过字符数组初始化字符串

1
2
3
let catCharacters: [Character] = ["C", "h", "a", "r"]
let catString = String(catCharacters)
print(catString)

字符串连接

字符串可以通过加法运算符” + “相加在一起,创建一个新的字符串

1
2
3
4
let string1 = "hello"
let string2 = " there"
var welcom = string1 + string2
print(welcom)

字符串末尾追加字符

1
2
let exclamationMark: Character = "!"
welcom.append(exclamationMark)

字符串插值

1
2
3
let multiplier = 3
let message = "\(multiplier) * 2.5 is \(Double(multiplier) * 2.5)"
print(message)

如果要在使用扩展字符串分隔符的字符串中使用字符串插值,需要在反斜杠后面添加与开头和结尾数量相同的扩展字符串分隔符。

1
print(#"6 * 7 is \#(6 * 7)"#)

如果是字符串可选项,在直接使用字符串插值的时候会报警告,避免警告有三种方式:

1
2
3
4
5
6
7
8
let str1: String? = "123"
print("str1 = \(str1!)") // 强制解包
print("str1 = \(String(describing: str1))") // 使用字符串方法
print("str1 = \(str1 ?? "空值")") // 使用空合并运算符
// 控制台打印如下信息:
//str1 = 123
//str1 = Optional("123")
//str1 = 123

计算字符数量

想要获得一个字符串中Character值的数量,可以使用count属性:

1
2
let unusualStr = "1234\t"
print(unusualStr.count) // 5

通过索引访问字符串的值

通过startIndex访问第一个字符,通过before lastIndex访问最后一个字符,lastIndex无法直接访问。

1
2
3
4
5
let greeting = "Helo, World!"
print(greeting[greeting.startIndex])
print(greeting[greeting.index(before: greeting.endIndex)])
print(greeting[greeting.index(after: greeting.startIndex)])
print(greeting[greeting.index(greeting.startIndex, offsetBy: 3)])

字符串插入操作

调用insert(_:at:)方法可以在一个字符串的指定索引插入一个字符,调用insert(contentsOf:at:)方法可以在一个字符串的指定索引插入一个字符串。

1
2
3
4
5
6
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
print(welcome) // 打印 hello!

welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
print(welcome) // 打印 hello there!

字符串移除操作

调用remove(at:)方法可以在一个字符串指定索引删除一个字符,调用removeSubrange(_:)方法可以在一个字符串的指定索引删除一个子字符串。

1
2
3
4
5
6
7
var welcome = "hello there!"
welcome.remove(at: welcome.index(before: welcome.endIndex))
print(welcome) // 打印 hello there

let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
print(welcome) // 打印 hello

子字符串

当你从字符串中获取一个子字符串 —— 例如,使用下标或者 prefix(_:)之类的方法 —— 就可以得到一个 Substring 的实例,而非另外一个 String。Swift 里的 Substring 绝大部分函数都跟 String 一样,意味着你可以使用同样的方式去操作 Substring 和 String。然而,跟 String 不同的是,你只有在短时间内需要操作字符串时,才会使用 Substring。当你需要长时间保存结果时,就把 Substring 转化为 String 的实例:

1
2
3
4
5
6
7
let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning 的值为 "Hello"

// 把结果转化为 String 以便长期存储。
let newString = String(beginning)

字符串相等

Swift提供了三种方式来比较文本值:字符串字符相等、前缀相等和后缀相等。

字符串/字符相等

字符串/字符可以用等于操作符(==)和不等于操作符(!=)。

1
2
3
4
5
6
7
8
9
10
11
12
13
var quotation1 = String("this is a test string")
var quotation2 = String("this is a test string")
var ptr1 = withUnsafePointer(to: &quotation1) { $0 }
var ptr2 = withUnsafePointer(to: &quotation2) { $0 }
print("quotation1地址:", ptr1)
print("quotation2地址:", ptr2)
if quotation1 == quotation2 {
print("quotation1 == quotation2")
}
// 控制台打印消息
// quotation1地址: 0x0000000102b1e090
// quotation2地址: 0x0000000102b1e0a0
// quotation1 == quotation2

参考链接

字符串和字符
Swift-06.指针(UnsafePointer)