上一章的链接:从0开始入门学习Swift 09 关于String字符串的相关操作 (上)
由于篇幅的原因,这一章接着继续学习String字符串的相关操作。
2.2 字符串的扩展使用
2.2.2 获取字符串 重点
查看是否包含某个字符:
var str3 = "ABCDEF"
//*查看是否包含某个字符/字符串 true为包含,fales为不包含
print(str3.contains("BK")) //必须为每个都包含才能为true
print(str3.contains(where: String.contains("BK"))) //只要有其中一个包含就可以为true
查看是否以某个字符串开头或者结尾:
//前缀 hasPrefix和后缀 hasSuffix,返回为true/false
var str3 = "ABCDEF"
print(str3.hasPrefix("AB")) //判读前缀
print(str3.hasSuffix("EF")) //判读后缀
在指定位置增加字符串:
var test_ins = "012345"
//传入增加的内容⬇️ 传入替换的位置⬇️
test_ins.insert(contentsOf: "这是增加的", at:test_ins.index(str.startIndex, offsetBy: 3))
print(test_ins)
在指定位置替换字符串 replaceSubrange:
//*在指定位置替换字符串 replaceSubrange
var test3 = "012345"
let st1 = test3.index(test3.startIndex, offsetBy: 1)//确定起始位置
let st2 = test3.index(test3.startIndex, offsetBy: 3)//确定结束位置
var rande = st1...st2 //区间运算符定义范围
//传入替换的区间⬇️ 传入替换的内容⬇️
test3.replaceSubrange(rande, with: "这是替换的部分")
test3.replaceSubrange(rande, with: "可以这样替换")
print(test3)
替换指定字符串 replacingOccurrences:
var test4 = "ABCDEFGHIJK"
var new_vl = test4.replacingOccurrences(of: "JK", with: "结尾")
print(new_vl)
删除某个字符串:
var test4 = "ABCDEFGHIJK"
test4.remove(at: test4.index(test4.startIndex, offsetBy: 2))
print(test4)
删除某个区间的字符串:
var test4 = "ABCDEFGHIJK"
test4.removeSubrange(test4.index(test4.startIndex, offsetBy: 1)...test4.index(test4.startIndex, offsetBy: 4))
print(test4)
用索引的形式遍历+反向:
var test4 = "ABCDEFGHIJK"
for item2 in (0 ..< test4.count).reversed(){
print(test4[ test4.index(test4.startIndex, offsetBy: item2)])
}
带引号输出:
var 引号输出 = #"“123213”"#
print(引号输出)
3.最终练习
不引入第三方变量的情况下,交换两个变量的值
var n = "1111111"
var m = "2222222"
n = n + m
print(n)
print("n变量 = " + String(n[n.index(n.startIndex, offsetBy: m.count)...n.index(n.startIndex, offsetBy: (n.count)-1)]))
print("m变量 = " + String(n[n.index(n.startIndex, offsetBy: 0)...n.index(n.startIndex, offsetBy: (m.count)-1)]))
本文深入讲解Swift中字符串的各种操作方法,包括如何检查字符串是否包含特定字符或子串、如何在指定位置插入或替换文本、以及如何删除指定字符或子串等实用技巧。
300

被折叠的 条评论
为什么被折叠?



