Swift 语言主要使用 String 和 Character 来存储字符数据。String 是字符串类型,Character 是字符类型,一个或多个字符组成一个字符串,不多说了,直接上代码!
//1.指定位置插入字符串
var string = "https:www.baidu.com"
let index = string.index(string.startIndex, offsetBy: 6)
string.insert(contentsOf: "//".characters, at: index)
//结果为:https://www.baidu.com
print("string of : \(string)")
string.insert("!", at: string.endIndex)//末尾加!
//结果为: https://www.baidu.com!
print("string end: \(string)")
//指定删除字符串
var string = " https://www.baidu.com"
let range0 = string.range(of: "!")
string.removeSubrange(range0!)
//结果为:https://www.baidu.com
print("remove string: \(string)")
////打印count 值,结果为: 21
print("string count : \(string.characters.count)")
//2.指定index 的位置是以后面开始,向左移动3位开始截取字符串
var string = " https://www.baidu.com"
let index1 = string.index(string.endIndex, offsetBy: -3)
//截取以index 的位置的字符串
let fromIndex = string.substring(from: index1)
//结果为: com
print("sub from string : \(fromIndex)")
//3.制定index 的位置是以前面开始,向右移动5位开始截取字符串
var string = " https://www.baidu.com"
let index2 = string.index(string.startIndex, offsetBy: 5)
//截取以index 的位置的字符串
let toIndex = string.substring(to: index2)
//结果为: https
print("sub to string : \(toIndex)")
//4.以某一特定位置来截取字符串
var string = " https://www.baidu.com"
let range = string.range(of: "baidu")
let lowerStr = string.substring(to: (range?.lowerBound)!)
//结果为: https://www.
print("to lower string: \(lowerStr)")
let upperStr = string.substring(to: (range?.upperBound)!)
//结果为: https://www.baidu
print("to upper string: \(upperStr)")
let lowerStr2 = string.substring(from: (range?.lowerBound)!)
//结果为: baidu.com
print("from lower string: \(lowerStr2)")
let upperStr2 = string.substring(from: (range?.upperBound)!)
//结果为: .com
print("from upper string: \(upperStr2)")
//5.字符串替换
var string = " https://www.baidu.com"
let range1 = string.range(of: "baidu")
string.replaceSubrange(range1!, with: "google".characters)
//结果为:https://www.google.com
print("replace string :\(string)")
//6.字符串转数组
var string = " https://www.baidu.com"
let arr = string.components(separatedBy: ".")
//结果为: ["https://www", "google", "com"]
print("arr item : \(arr)")
//7.数组转字符串
var string = " https://www.baidu.com"
let strItem = arr.joined(separator: "#")
//结果为:https://www#google#com
print("strItem: \(strItem)")
网友评论