Swift 的 String类型桥接到了基础库中的 NSString类。Foundation 同时也扩展了所有 NSString 定义的方法给 String 。也就是说,如果你导入 Foundation ,就可以在 String 中访问所有的 NSString 方法,无需转换格式
1、 字符串字面量
let someString = "Some string literal value"
2、初始化一个空字符串
var emptyString = ""
var anotherEmptyString = String()
3、判断字符串是否为空
if emptyString.isEmpty {
print("Nothing to see here")
}
4、 操作字符
for character in "Dog!?" {
print(character)
}
let catCharacters: [Character] = ["C", "a", "t", "!", "?"]
let catString = String(catCharacters)
print(catString)
5、 字符串的拼接
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
welcome += string2
print(welcome)
6、 字符串的穿插值
let name = "zhang"
let age = 19
let height = 1.87
let message = "my name is\(name) my age is \(age) my height \(height)"
let personStr = String(format: "my name is %@ my age is %d my height %f", name,age,height)
print(message,personStr)
7、字符串的长度
let unusualMenagerie = "Koala ?, Snail ?, Penguin ?, Dromedary ?"
print(unusualMenagerie.count)
8、字符串的索引
let greeting = "Guten Tag!"
print(greeting[greeting.startIndex]) //greeting.startIndex 这是个数值
print(greeting[greeting.index(before: greeting.endIndex)])
print(greeting[greeting.index(after: greeting.startIndex)])
let index = greeting.index(greeting.startIndex, offsetBy: 7)
print(greeting[index])
9、 使用 indices属性来访问字符串中每个字符的索引
for index in greeting.indices {
print("\(greeting[index]) ", terminator: "")
}
10、 插入
var insertWelcome = "hello"
insertWelcome.insert("!", at: insertWelcome.endIndex)
insertWelcome.insert(contentsOf: " there", at: insertWelcome.index(before: insertWelcome.endIndex))
print(insertWelcome)
11、删除
let reoveOne = insertWelcome.remove(at: insertWelcome.index(before: insertWelcome.endIndex))
print(reoveOne)
let reoveTwo = insertWelcome.index(insertWelcome.endIndex, offsetBy: -6)..<insertWelcome.endIndex
print(insertWelcome.removeSubrange(reoveTwo))
12、 字符串的截取
let timeString = "http://www.baidu.com"
let header = (timeString as NSString).substring(to: 3)
print(header)
let middle = (timeString as NSString).substring(with: NSMakeRange(7, 8))
print(middle)
let footer = (timeString as NSString).substring(from: 7)
print(footer)
13、字符串的比较
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")
}
网友评论