Swift学习笔记03:字符和字符串

字符串字面量

Swift 的字符串是值类型,采用 Unicode 编码。

字符串用一对双引号括起来,类型为String

let someString = "Some string literal value"

如果字符串需要跨行,可以用三个双引号括起来。

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."
"""

结尾的\表示这里不换行。结尾的"""前面如果有 n 个空格,那么该多行字符串每一行前面都会忽略 n 个空格。

字符串中以\开头的被称为转义字符,如空字符\0、反斜杠\\、水平制表符\t、换行符\n、回车符\r、双引号"、单引号'等。\u{n}表示任意 Unicode 字符,其中n是 1~8 个 16 进制数字。

如果在引号前后都加上#,字符串中的转移符号就不会生效。但如果转义符号后面也有#,则该转义字符仍然会生效。

#"Line1\nLine2\#Line3"#
// Line1\nLine2
// Line3

初始化空字符串

""String()创建空字符串,isEmpty属性检查字符串是否为空。

var emptyString = String()
if emptyString.isEmpty {
    print("Nothing in emptyString")
}

操作字符

使用for来遍历字符串中的每个字符。

for ch in "Hello" {
    print(ch)
}

创建一个独立的字符常量或变量:

let ch: Character = "!"

通过字符数组创建字符串:

let chList: [Character] = ["C", "a", "t"]
let chString = String(chList)	// Cat

count属性获取字符串的长度。

使用+将两个字符串连接,+=在已有的字符串后面追加字符串,append()在末尾追加字符。

使用\()将变量的值插入到字符串中。

访问和修改字符串

字符串无法通过整数来索引,只能使用startIndex属性获取字符串首个字符的位置,或用endIndex属性获取字符串最后一个字符之后的位置。index(before:)index(after:)方法访问给定索引的前后,如果是更远的索引,使用index(_:offsetBy:)方法。

let greeting = "Guten Tag!"
print(greeting[greeting.startIndex])	// G
print(greeting[greeting.index(before: greeting.endIndex)])	// !
print(greeting[greeting.index(after: greeting.startIndex)])	// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
print(greeting[index])	// a

indices属性访问字符串的每个字符的索引:

for index in greeting.indices {
    print("\(greeting[index]) ", terminator: "")
}

插入和删除

使用insert(_:at:)插入字符,insert(contentsOf:at:)插入字符串。

var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))

使用remove(at:)删除字符,removeSubrange(_:)删除一段字符。

welcome.remove(at: welcome.index(before: welcome.endIndex))
let range = welcome.index(welcome.endIndex, offsetBy: =6)..<welcome.endIndex
welcome.removeSubrange(range)

子字符串

[]获取的是字符串的映射,要将其保存为真正的字符串需要用String()

let greeting = "Hello, world!"
let index = greeting.index(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]	// Hello
let newString = String(beginning)

字符串比较

两个字符串或字符可以用==!=来比较。两个字符可能字型一致但 Unicode 编码不一致,它们也被认为是不等的。

hasPrefix()hasSuffix()检查字符串是否具有特定的字符串前缀或后缀。

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值