美文网首页
3、Swift Strings and Characters

3、Swift Strings and Characters

作者: Vergil_wj | 来源:发表于2017-08-22 16:48 被阅读9次
  • 字符串String是由一系列的字符Characters组成的
字符串字面量
let someString = "Some string literal value"

多行显示,使用三个双引号
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."
"""
multilineStringWhitespace.png
字符串中的特殊字符
\n:空字符,\\:反斜杠,\t:制表符,\n:换行,\r:回车,\":双引号,\':单引号
初始化空字符串
var emptyString = ""              
var anotherEmptyString = String()
//两个字符创都为空

判断空字符串:
if emptyString.isEmpty {
    print("Nothing to see here")
}
字符串可变性
var variableString = "Horse"
variableString += " and carriage"
// variableString 为 "Horse and carriage"
字符串是值类型
swift的string是值类型,那么当其进行常量、变量赋值操作或在函数/方法中传递时,会进行值拷贝。 任何情况下,都会对已有字符串值创建新副本,并对该新副本进行传递或赋值操作
使用字符
可以通过for-in便利string中每个字符:
for character in "Dog!🐶" {
    print(character)
}
// D
// o
// g
// !
// 🐶

sting可以通过字符数组构造:
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!🐱"
链接字符串和字符
直接相加就可以:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"

通过 append() 将 Character 连接到 string:
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"

注意:不能在已经存在的Character后拼接string或character,因为character只能包含一个字符

多行拼接的话会拼接的最后一行:
let badStart = """
one
two
"""
let end = """
three
"""
print(badStart + end)
// one
// twothree
 
let goodStart = """
one
two
 
"""
print(goodStart + end)
// one
// two
// three
字符串插值
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
计算字符
关键字:count
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
print("unusualMenagerie has \(unusualMenagerie.count) characters")
// Prints "unusualMenagerie has 40 characters"
获取和修改String
1、获取string
string索引:
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a

超出边界崩溃:
greeting[greeting.endIndex] // Error
greeting.index(after: greeting.endIndex) // Error

使用indices属性获取String中每个字符:
for index in greeting.indices {
    print("\(greeting[index]) ", terminator: "")
}
// Prints "G u t e n   T a g ! "
2、插入和删除
插入字符串:
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"
 
welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"

删除字符串:
使用 remove(at:)方法:
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"
 
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"
子串
let greeting = "Hello, world!"
let index = greeting.index(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning is "Hello"
 
// Convert the result to a String for long-term storage.
let newString = String(beginning)
比较字符串

Swift提供了3种比较方式:string and character equality;prefix equality; suffix equality;

1、字符串相等
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    print("These two strings are considered equal")
}
2、前后缀相等
let romeoAndJuliet = [
    "Act 1 Scene 1: Verona, A public place",
    "Act 1 Scene 2: Capulet's mansion",
    "Act 1 Scene 3: A room in Capulet's mansion",
    "Act 1 Scene 4: A street outside Capulet's mansion",
    "Act 1 Scene 5: The Great Hall in Capulet's mansion",
    "Act 2 Scene 1: Outside Capulet's mansion",
    "Act 2 Scene 2: Capulet's orchard",
    "Act 2 Scene 3: Outside Friar Lawrence's cell",
    "Act 2 Scene 4: A street in Verona",
    "Act 2 Scene 5: Capulet's mansion",
    "Act 2 Scene 6: Friar Lawrence's cell"
]
前缀:
var act1SceneCount = 0
for scene in romeoAndJuliet {
    if scene.hasPrefix("Act 1 ") {
        act1SceneCount += 1
    }
}
print("There are \(act1SceneCount) scenes in Act 1")
// Prints "There are 5 scenes in Act 1"
后缀:
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
    if scene.hasSuffix("Capulet's mansion") {
        mansionCount += 1
    } else if scene.hasSuffix("Friar Lawrence's cell") {
        cellCount += 1
    }
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// Prints "6 mansion scenes; 2 cell scenes"
Unicode

Unicode 是一个国际标准,用于文本的编码和表示。 它使您可以用标准格式表示来自任意语言几乎所有的字符,并能够对文本文件或网页这样的外部资源中的字符进行读写操。Swift 的字符串和字符类型是完全兼容 Unicode 标准的。

1、Unicode Scalars

Unicode 中每一个字符都可以被解释为一个或多个 unicode 标量。 字符的 unicode 标量是一个唯一的21位数字(和名称),例如U+0061表示小写的拉丁字母A ("a"),U+1F425表示小鸡表情 ("🐥")

2、字符串的 Unicode 表示(Unicode Representations of Strings)

Swift 提供了几种不同的方式来访问字符串的 Unicode 表示:
a、可以利用for-in来对字符串进行遍历,从而以 Unicode 字符的方式访问每一个字符值。
b、另外,能够以其他三种 Unicode 兼容的方式访问字符串的值:
UTF-8 代码单元集合 (利用字符串的utf8属性进行访问)
UTF-16 代码单元集合 (利用字符串的utf16属性进行访问)
21位的 Unicode 标量值集合 (利用字符串的unicodeScalars属性进行访问)

UTF-8
UTF8.png
for codeUnit in dogString.utf8 {
    print("\(codeUnit) ", terminator: "")
}
print("")
// Prints "68 111 103 226 128 188 240 159 144 182 "
UTF-16
UTF16.png
for codeUnit in dogString.utf16 {
    print("\(codeUnit) ", terminator: "")
}
print("")
// Prints "68 111 103 8252 55357 56374 "
Unicode Scalar
UnicodeScalar.png
for scalar in dogString.unicodeScalars {
    print("\(scalar.value) ", terminator: "")
}
print("")
// Prints "68 111 103 8252 128054 "

for scalar in dogString.unicodeScalars {
    print("\(scalar) ")
}
// D
// o
// g
// ‼
// 🐶

相关文章

网友评论

      本文标题:3、Swift Strings and Characters

      本文链接:https://www.haomeiwen.com/subject/msxirxtx.html