字符串是是一系列字符的集合,Swift中的字符串通过 String
类型来表示。 一个 String
的内容可以用许多方式读取,包括作为一个 Character
值的集合。
Swift 的
String
类型与 FoundationNSString
类进行了无缝桥接。Foundation 也可以对String
进行扩展,暴露在NSString
中定义的方法。 这意味着,如果你在String
中调用这些NSString
的方法,将不用进行转换。
字符串的表示可以是一对 "" 双引号
let someString = "Some string literal value"
多行字符串用一对 """~"""三引号,多行字符串不会对其中的转义字符处理
let someString = """
The White Rabbit put on his spectacles. "Where shall I begin,
please your Majesty?" he asked.
"Begin at the beginning," the King said gravely, "and go on
till you come to the end; then stop."
""" // 原样输出
创建字符串
通过字面量,创建
//字面量创建 var 修饰 可变
var string = "Literal"
var nullString = "" //空串
// 构造方法 let 修饰 不可变
let string = String("ss")
let nullString = String() //空串
用C字符串创建
//swift中不能直接写C语言,需要用到swift指针
var validUTF8:[UInt8] = [97,98,99,100,0]
var uint8String = String(cString: validUTF8)
print(uint8String)
//苹果推荐的做法
let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
validUTF8.withUnsafeBufferPointer { ptr in
let s = String(cString: ptr.baseAddress!)
print(s)
}
字符串格式化
//format格式和OC中一致
单个变量format
var floatNum:Float = 5.0
var formatString1 = String(format: "float:%f", arguments: [floatNum])
var formatString2 = String(format: "float:%f", arguments: [5.0])
字符串用%@
var name = String("lili")
var formatString3 = String(format: "swift:%@", arguments: [name])
多个变量
var formatString3 = String(format: "float:%f-%d-%c", arguments: [5.0,2,97])
//或者
var formatString = String(format: "format string:%d-%.2f-%c",11,5.0,97)
字符串插值
var interpolationString = "interpolation:\(floatNum):String"
print(interpolationString)//interpolation:5.0:String
字符串拼接,插值,格式化都可以实现拼接效果
// 通过 appending(:)
let string1 = "name"
var string2 = "age"
var string = string2.appending(string1)
//等效的写法 ,+
let string1 = "name"
let string2 = "age"
var string = string1 + string2
//字符串插值
var string = "\(string2)\(string1)"
//格式化
var string = String(format: "%@%@", arguments: [string1,string2])
Index
字符串索引String.Index
swift中的字符串不能直接通过下表[]整数的形式访问
var line = "I want magic"
line[0]// 编译报错
indices
属性会创建一个包含全部索引
for i in line.indices{
print(line[i])// OK的
}
除此之外,index(_:offsetBy:)获取指定位置的索引
var version = "10.11.12"
//对于一个确定的字符串,能直接获取到它的startIndex,endIndex
//endIndex 是最后一个字符之后的索引
var prefixIndex = version.startIndex
var suffixIndex = version.endIndex
//获取 第二个索引
var secondIndex = version.index(prefixIndex, offsetBy: 2)
//获取倒数第二个索引
var reversalSecondIndex = version.index(suffixIndex, offsetBy: -2)
//当前索引的下一个
var afterIndex = version.index(after: prefixIndex)
//如果超出限制,返回nil
var maxIndex = version.index(prefixIndex, offsetBy: 100, limitedBy: suffixIndex)
//获取任意字符的索引,返回可选
var index = line.firstIndex(of: "0") ?? line.endIndex
有了String.Index字符串截取,通过下标[]运算访问
//substring(to:)已弃用
//从首位到索引位置的字符串
print(version.substring(to: secondIndex))//10
print(version.substring(to: reversalSecondIndex))//10.11.
print(version.substring(to: afterIndex))//1
//倒数到索引位置的字符串
//substring(from:)已弃用
print(version.substring(from: secondIndex))//.11.12
print(version.substring(from: reversalSecondIndex))// 12
print(version.substring(from: afterIndex))// 0.11.12
// range 注意区间右边越界 suffixIndex 是最后一个字符之后的索引
print(version[secondIndex]) // .
print(version[prefixIndex..<suffixIndex]) //"10.11.12"
print(version[prefixIndex...suffixIndex]) //越界 异常
print(version[secondIndex...reversalSecondIndex])//.11.1
print(version[index]) // 0
print(version[...index])//10
print(version[index...])//0.11.12
print(line[...])//10.11.12
字符串替换,删除,插入
// : 替换 -
var time = "2021:1:1"
var newTime = time.replacingOccurrences(of: ":", with: "-")
print(newTime)//2021-1-1
// 删除 用空字符代替
var newTime1 = time.replacingOccurrences(of: ":", with: "")
//替换一段字符
var strat = time.index(time.startIndex, offsetBy: 4)
var end = time.index(time.startIndex, offsetBy: 5)
var newTime2 = time.replacingCharacters(in: strat..<end, with: "AAAA")
print(newTime2)//2021AAAA1:1
// 删除 单个字符
time.remove(at: time.index(time.startIndex, offsetBy: 4))
print(time)//20211:1
//删除一段字符
time.removeSubrange(time.range(of: "2021")!) //:1:1
time.removeSubrange(time.startIndex..<time.endIndex)// 空字符串
//等效写法
time.removeAll()
插入字符 insert(_:at:)
//在指定索引 前面 插入字符
time.insert("A", at: strat)
插入字符串 insert(contentsOf:at:)
//在指定索引 前面 插入多个字符
time.insert(contentsOf: "BBBB", at: strat)
过滤trimmingCharacters(in:)
会对字符串的开头和结尾过滤处理
var time = " 2021:1:1 "
//过滤前后空格
var nowhitespaces = time.trimmingCharacters(in: .whitespaces)
// 20BBBB21:1:1
//filter
time.filter { $0.isNumber }
// 202111
由于字符串遵守Sequence协议,所以Sequence系列方法也都适用
字符串分割
split
根据单个字符分割
// 按照 : 分割 返回数组
var sp = time.split(separator: ":")//["UTC BBBB2021-01-28 02", "39", "40 +0000"]
//根据满足条件的字符,分割 返回数组
var sp1 = time.split {$0.isNumber}//["UTC BBBB", "-", "-", " ", ":", ":", " +"]
//根据 空格分割 限制最大分割次数maxSplits
var sp2 = time.split(separator: " ", maxSplits: 1, omittingEmptySubsequences: true)
print(sp2)//["UTC", "BBBB2021-01-28 02:39:40 +0000"]
//omittingEmptySubsequences = false 返回的集合包含 空字符符
var time = "UTC 2021-01-28 02:39:40 +0000"
var sp5 = time.split(maxSplits: 100, omittingEmptySubsequences: false) {$0.isWhitespace}
print(sp5)//["UTC", "BBBB2021-01-28", "", "", "", "", "", "", "", "", "", "", "02:39:40", "+0000"]
components
根据 子串 分割
//根据 magic 子串 分割
let line = "I want magic I want magic I want magic I want magic I want magic"
line.components(separatedBy: "magic")
//["I want ", " I want ", " I want ", " I want ", " I want ", ""]
//自定义字符集CharacterSet
line.components(separatedBy: CharacterSet.init(charactersIn: "It"))
//["", " wan", " magic ", " wan", " magic ", " wan", " magic ", " wan", " magic ", " wan", " magic"]
如果是从前缀开始或者后缀截取字符串,可以通过prefix(:)
和suffix(:)
line. prefix(5) // I want
line.suffix(5) // magic
子字符串SubString
通过下标[],等方法会得到一个SubString类新的字符串,在没有对原字符串写操作之前,它会复用原String的内存空间,因此SubString
不适合长期存储,最好转换成String保存
var subIndex = line.index(line.startIndex, offsetBy: 4)
var subLine = line[line.startIndex...subIndex] //subString
let newString = String(subLine)//String
网友评论