声明
let emptyString = ""
let str = "abc"
let str1: String = "abc"
// str2赋值后才可以使用 并且不能改变
let str2: String?
声明多行字符串
let numbers = let numbers = """
1
2
3
4
5
"""
print("numbers === \(numbers)")
输出结果如下所示:
字符串插值
使用\()
来进行插值,与Objective-C
的stringWithFormat
方法类似,其实就是使用占位符格式化输出.
let str = "6 times 7 is \(6 * 7)."
print(str)
输出结果:
插值使用起来确实比OC
的更加方便灵活
let str: String = "abc"
print("str is \(str)")
Raw String
swift
的转义写法,可以在字符串中输出特殊字符
print(#"6 times 7 is \(6 * 7)."#)
输出结果如下所示:
这个时候如果想要使插值生效的话,可以在反斜杠后面添加与首尾同等数量的#
print(#"6 times 7 is \#(6 * 7)."#)
输出结果:
字符串常用操作
判空
let emptyString = ""
if emptyString.isEmpty {
print("emptyString is empty")
}
取出字符串中某个字符
-
取出某个个字符
let welcome = "Hello, world!" // 取出第一个字符 welcome[welcome.startIndex] // 取出最后一个字符 welcome[welcome.index(before: welcome.endIndex)] // 第二个字符 welcome[welcome.index(after: welcome.startIndex)] /// 取出第一个字符值后面第二个字符 welcome[welcome.index(welcome.startIndex, offsetBy: 2)]
-
插入字符
var str = "abc" str.insert("d", at: str.endIndex) /// 结果 str = abcd
-
插入字符串
str.insert(contentsOf: "efg", at: str.endIndex) /// 结果 str = abcdefg
-
移除字符
// 移除首字符 str.removeFirst() // 移除最后一个字符 str.removeLast() str.remove(at: str.index(before: str.endIndex)) print(str) /// str = adcdef
-
移除字符串
var string = "abcdef" let range = string.index(str.endIndex, offsetBy: -2)..<string.endIndex string.removeSubrange(range) /// str = abcd // 移除所有 string.removeAll() /// str = ""
-
字符串长度
var str1 = "123"
str1.count
-
字符串判断
let string1 = "123456" let string2 = "123" if string1 == string2 { print("string1与string2相等") } // 前缀相等性 string1.hasPrefix(string2) // 后缀相等性 string1.hasSuffix(string2)
-
获取子字符串
let title = "Hello, world!" // 截取前缀 title.prefix(5) // 截取后缀 title.suffix(6)
-
分割字符串
let nameStr = "John,Andy,Nancy" let names = nameStr.split(separator: ",")
-
字符串拼接
var starStr = "abc" let endStr = "efg" starStr.append(endStr)
注意:
- 使用下标或者类似prefix(_:)的方法得到的字符串是Substring类型
- Substring拥有String的大部分方法, Substring可以转为String, (Substring是为了内存考虑,在更改或者使用String初始化Substring之前, Substring都指向原来的内存)
- String和Substring都遵循StringProtocol协议, 在日常工作中, 需要一些定义字符串的操作函数,参数使用StringProtocol
拓展
从上面我们的一系列操作中,我们可以看出Swift
的字符串不支持下标的操作,全部采用String.index
进行操作,使用起来确实更加复杂,why?