swift5笔记(一):从字符串开始
2022-10-30 本文已影响0人
Harry__Li
字符串的创建
初始化字符串
let nameStr = ""
let nameStr1 = String()
//推断类型
let str = "test"
//指定类型
let testStr :String = "name"
字符串的拼接
//字符串拼接
let str2 = str + testStr
print(str2)
let str3 = str.appending(testStr)
print("拼接的字符串是:\(str3)")
字符串其他属性
let str6 = String(format: "学习的第一行代码是:%@", greeting)
print(str6)
//字符串的长度
print(str6.count)
//判断是否为空
print(str6.isEmpty)
//遍历字符串
for char in str6 {
print(char)
}
删
var deleteStr = "这是一个要删除的字符串"
print(deleteStr[deleteStr.startIndex])
//删除首字母
deleteStr.removeFirst()
//删除最后的字母
deleteStr.removeLast()
print(deleteStr)
//删除定制位置的字符串 删除一个字符,从首字符开始
deleteStr.remove(at: deleteStr.index(deleteStr.startIndex, offsetBy: 2))
print(deleteStr)
deleteStr.remove(at: deleteStr.index(deleteStr.endIndex, offsetBy: -1))
print(deleteStr)
//删除从首字母的3个字符
var str8 = "hello world"
str8.removeFirst(3)
print(str8)
var str9 = "jjjjdkdkfjfhslehjf"
str9.removeLast(5)
print(str9)
//删除指定位置的字符
var str10 = "dkghrjdkejfjfgsef"
let start = str10.index(str10.startIndex, offsetBy: 4)
let end = str10.index(str10.endIndex, offsetBy: -4)
str10.removeSubrange(start...end)
print(str10)
插入
var inserstr = "ABCDEFGH"
inserstr.insert("x", at: inserstr.index(inserstr.startIndex, offsetBy: 4))
inserstr.insert(contentsOf: "abab", at: inserstr.index(inserstr.startIndex, offsetBy: 1))
//字符串替换
var replaceStr = "世界你好啊 我是地球"
replaceStr.replacingOccurrences(of: "你好", with: "和平")
replaceStr.replaceSubrange(replaceStr.index(replaceStr.endIndex, offsetBy: -2)..<replaceStr.endIndex, with: "hello world")
字符串截取
let teststr5 = "abcdefgfhfh"
//头部截取
print(teststr5.prefix(4))
//尾部截取
print(teststr5.suffix(5))
//range截取
let index2 = teststr5.index(teststr5.startIndex, offsetBy: 3)
let index3 = teststr5.index(teststr5.startIndex, offsetBy: 8)
let sl = teststr5[index2...index3]
print(sl)
//获取指定位置字符串
let range = teststr5.range(of: "fg")
print(teststr5[teststr5.startIndex..<range!.lowerBound])
print(teststr5[teststr5.startIndex..<range!.upperBound])