Swift4.2基础学习笔记(五)

2018-10-11  本文已影响0人  清灬影

参考资料与链接https://www.cnswift.org

字符串字面量

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."
"""
//反斜杠转义
let threeDoubleQuotes = """
Escaping the first quote \"""
Escaping all three quotes \"\"\"
"""

初始化一个空字符串

var emptyString = ""               // empty string literal
var anotherEmptyString = String()  // initializer syntax
// these two strings are both empty, and are equivalent to each other
//判断一个string值是否为空
if emptyString.isEmpty{
    print("Nothing to see here")
}

字符串可变性

var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"
 
let constantString = "Highlander"
constantString += " and another Highlander"
// this reports a compile-time error - a constant string cannot be modified

字符串是值类型

Swift 的 String类型是一种值类型。如果你创建了一个新的 String值, String值在传递给方法或者函数的时候会被复制过去,还有赋值给常量或者变量的时候也是一样。每一次赋值和传递,现存的 String值都会被复制一次,传递走的是拷贝而不是原本。

操作字符

通过 for-in循环遍历 String 中的每一个独立的 Character值

for character in "Dog!?" {
    print(character)
}
// D
// o
// g
// !
// ?

String值可以通过传入 Character值的字符串作为实际参数到它的初始化器来构造:

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"
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"

注意
Character值能且只能包含一个字符。

字符串插值

let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"

注意
作为插值写在圆括号中的表达式不能包含非转义的双引号 (" ")或者反斜杠 ( \),并且不能包含回车或者换行符。它们可以包含其他字符串字面量。

上一篇下一篇

猜你喜欢

热点阅读