Swift 中字符串基本知识(一)- Character
Character 是什么?
Apple 官方文档定义:
A single extended grapheme cluster that approximates a user-perceived character.
单一扩展字符群,用来表示用户可以感知的字符。
简单的说就是用来表示单个字符的结构体。
具体实现代码如下(省略了一些代码和修饰符):
public struct Character {
/// Creates a character containing the given Unicode scalar value.
public init(_ content: Unicode.Scalar)
/// Creates a character from a single-character string.
public init(_ s: String)
/// The ASCII encoding value of this character, if it is an ASCII character.
public var asciiValue: UInt8? { get }
}
怎么使用?
怎么初始化一个字符 Character?
- 使用
Unicode
标量值
let airplane = Unicode.Scalar(9992)!
let character = Character(airplane)
print(character)
// ✈
- 使用单个字符的字符串
let exclamationMark: Character = "!"
// or
let exclamationMark = Character("!")
怎么和字符串 String 一起使用?
- 字符串和字符数组如何相互转化
字符串转字符数组
let string = "Dog!🐶"
let characters = Array(string) // Array<Character>
print(characters)
// ["D", "o", "g", "!", "🐶"]
字符数组转字符串
let characters: [Character] = ["D", "o", "g", "!", "🐶"]
let string = String(characters)
print(string)
// "Dog!🐶"
- 字符串如何遍历所有字符
let string = "Dog!🐶"
for character in string {
print(character)
}
// D
// o
// g
// !
// 🐶
- 如何得到字符串中指定 index 的字符?
func getChar(s: String, at offset: Int) -> Character {
let index = s.index(s.startIndex, offsetBy: offset)
return s[index]
}