最近写基于Swift 4.0的项目,每次用到String的时候就要去查询半天,再与NSString对比,实在忍受不了查找了,就自己总结一下常用的用法吧,正好也是第一次尝试写文章,希望能每周坚持写一篇总结。
废话不多说开始总结:
1、正常用法:
let greeting ="Welcome"
2、多行字符串文字Swift 4.0新的用法:
如果要使用换行符来使源代码更容易阅读,但是您不希望换行符成为字符串值的一部分,请在这些行的末尾写入反斜杠(\)
同时注意特殊符号的用法 \" , ' , \t , \0 , \n , \r , \\ 等等
let quotation = """
\"Hello this is Multiline \
String Literals
please input you name
"哈哈哈,是不是很爽"
what are you doing
"""
3、初始化空字符串
//初始化空字符串
var emptyString = ""
var otheremptyString = String()
//判断是否是空字符串
if emptyString.isEmpty {
print("空字符串")
}
//赋值
otheremptyString = "Hello"
//count 统计长度
print(otheremptyString.count)//此处输出5
//以C语言的字符串初始化
let cStr = String(cString:...)
//以URL初始化
let urlStr = String(contentsOf: URL, encoding: String.Encoding)
//以File路径初始化
let fileStr = String(contentsOfFile: String, encoding: String.Encoding)
//以Data类型初始化
let urlStr = String(data: Data, encoding: String.Encoding)
// 格式化初始字符串
let f = 123.4322
let fStr = String(format: "%.2f", f)
print("fStr = \(fStr)")
// 以subString 初始化字符串
let substr = String(Substring)
4、访问和修改字符串
let greeting = "Guten Tag!"
let start = greeting[greeting.startIndex]
print("start = \(start)")//start = G
let beforeEnd = greeting[greeting.index(before: greeting.endIndex)]
print("beforeEnd = \(beforeEnd)")//beforeEnd = !
let afterStart = greeting[greeting.index(after: greeting.startIndex)]
print("afterStart = \(afterStart)")//afterStart = u
let index = greeting.index(greeting.startIndex, offsetBy: 6)
print("index = \(index)")
let m = greeting[index]
print("m = \(m)")//m = T
//insert方法貌似已经被去掉
let r = greeting.remove(at: index)
print("r = \(r)")//r = T
print("greeting = \(greeting)")//greeting = Guten ag!
let range = greeting.index(greeting.endIndex, offsetBy: -5)..<greeting.endIndex
greeting.removeSubrange(range)
print("greeting = \(greeting)") //greeting = Gute
5、拼接字符串 + 或 += 或 append
let k = emptyString + " dsjjdjsjd"
print(k)
otheremptyString += " Boy!"
print(otheremptyString)
let ex: Character = "!"
otheremptyString.append(ex)
print(otheremptyString)
6、比较或截取字符串
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")
}
let hasPreFixStr = "Welcome Hello World!"
if hasPreFixStr.hasPrefix("W") {
print("以W开头")
}
if hasPreFixStr.hasSuffix("!") {
print("以!结尾")
}
let dogStr = "Dog!!🐶"
for scalar in dogStr.unicodeScalars {
print("\(scalar) ")
}//UnicodeScalar, 可以直接打印unicode字符
let pre = hasPreFixStr.prefix(3)
let suf = hasPreFixStr.suffix(3)
let dropFirst = hasPreFixStr.dropFirst()
let dropLast = hasPreFixStr.dropLast()
//注意这些pre、suf、dropFirst、dropLast是SubSequence也就是Substring类型,要使用再转换成String
let newStr = String(suf)
7、字符串按对应的字符分割为数组
let line = "BLANCHE: I don't want realism. I want magic!"
print(line.split(separator: " "))
//["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]
print(line.split(separator: " ", maxSplits: 1))
//["BLANCHE:", " I don\'t want realism. I want magic!"]
print(line.split(separator: " ", omittingEmptySubsequences: false))
//["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]