//字符串查询
var str = "天空上有美丽的星球"
str.contains("美") //包含字符
str.hasSuffix("球")// 后轴
str.hasPrefix("天") //前缀
str.appending("123") //往后添加
let index = str.index(str.startIndex, offsetBy: 3) //插入到指定位置
str.insert(contentsOf: "hello", at: index)
//替换
let index1 = str.index(str.startIndex, offsetBy: 1)
let index2 = str.index(str.startIndex, offsetBy: 2)
let range = index1..<index2
str.replaceSubrange(range, with: "AAABBB")
//替换指定字符串
var value = str.replacingOccurrences(of: "空上", with: "中国")
//删除
var value = str.remove(at: str.index(str.startIndex, offsetBy: 2))
//范围删除
var a = str.index(str.startIndex, offsetBy: 1)
var b = str.index(str.startIndex, offsetBy: 3)
str.removeSubrange(a...b)
print(str)
//字符串截取
var str = "天空上有美丽的星球"
print(str[str.startIndex]) //开始的字符
str[str.index(before: str.endIndex)] //最后的一个字符
let tmp = str[str.index(str.startIndex, offsetBy: 3)] //一个
let a = str.index(str.startIndex, offsetBy: 2)
let b = str.index(str.startIndex, offsetBy: 4)
str[a...b] //范围
var c = str.firstIndex(of: "美") ?? str.startIndex //返回一个范围
str.prefix(4) //从前开始截取
let i = str.index(str.endIndex, offsetBy: -2) //从后往前截取
str[i..<str.endIndex]
str[str.index(after: str.startIndex)] //后一位
print()
网友评论