Swift字符串的常见操作

2021-05-29  本文已影响0人  一个栗

字符串的可变性

字符串是值类型

操作字符

for character in "Dog!🐶" {
    print(character)
}

let catCharacters:[Character] = ["C","a","t","!","🐶"]
let catString = String(catCharacters)
print(catString)

打印结果如下:
D
o
g
!
🐶
Cat!🐶

字符串拼接

字符串插值

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

打印结果如下:
3 times 2.5 is 7.5
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
print(#"Write an interpolated string in Swift using \(multiplier)."#)
print(#"6 times 7 is \#(6 * 7)."#)

打印结果如下:
Write an interpolated string in Swift using \(multiplier).
6 times 7 is 42.

值类型

var welcome = "hello"
var welcome1 = welcome
print(welcome == welcome1)
welcome1.append(",")
print(welcome, welcome1)

打印结果如下:
true
hello hello,
上一篇 下一篇

猜你喜欢

热点阅读