在Swift中,处理字符串有多种方法,包括字符串的创建、修改、拼接、截取等。
let str1 = "Hello, Swift!"
let str2 = """
This is a multi-line string.
It can have multiple lines.
"""
let name = "Alice"
let greeting = "Hello, " + name
let age = 25
let message = "I am \(age) years old."
let str = "Hello"
let length = str.count
print(length) // 输出 5
let str = "Hello, Swift!"
let range = str.index(str.startIndex, offsetBy: 7)..<str.index(str.endIndex, offsetBy: -1)
let subStr = str[range]
print(subStr) // 输出 Swift
let str = "Hello, Swift!"
let upperStr = str.uppercased()
let lowerStr = str.lowercased()
print(upperStr) // 输出 HELLO, SWIFT!
print(lowerStr) // 输出 hello, swift!
以上是一些常用的字符串处理方法,在实际开发中可以根据需求选择合适的方法来处理字符串。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Swift属性观察器如何确保数据一致性