Swift的字符串类型String,跟OC的NSString,还是有较大不同的
String的创建与拼接
截屏2022-03-06 下午2.45.10.pngString的插入与删除
var str:String = "1_2"
print(str,str.startIndex,str.endIndex)
// 1 Index(_rawBits: 1) Index(_rawBits: 65537)
从上面打印可以看出,startIndex与endIndex与我们所认知的是不同的,OC里可能startIndex是0,endIndex是2,但是在Swift里就不一样了
var str:String = "1_2"
// print(str,str.startIndex,str.endIndex)
str.insert("_", at: str.endIndex)
print(str) // 1_2_
str.insert(contentsOf: "3_4", at: str.endIndex)
print(str) // 1_2_3_4
str.insert(contentsOf: "666 ", at: str.index(after: str.startIndex))
print(str) // 1666 _2_3_4
str.insert(contentsOf: "888", at: str.index(before: str.endIndex))
print(str) // 1666 _2_3_8884
str.insert(contentsOf: "hello", at: str.index(str.startIndex, offsetBy: 4))
print(str) // 1666hello _2_3_8884
str.remove(at: str.firstIndex(of: "1")!)
print(str) // 666hello _2_3_8884
str.removeAll() {
$0 == "6"
}
print(str) // hello _2_3_8884
let range = str.index(str.endIndex, offsetBy: -4)..<str.index(before: str.endIndex)
str.removeSubrange(range)
print(str) // hello _2_3_4
Substring
截取字符串
var str = "1_2_3_4_5"
var substr1 = str.prefix(3)
print(substr1) // 1_2
var substr2 = str.suffix(3)
print(substr2) // 4_5
var range = str.startIndex..<str.index(str.startIndex, offsetBy: 3)
var substr3 = str[range];
print(substr3) // 1_2
print(substr3.base) // 1_2_3_4_5
var str2 = String(substr3)
print(str2) // 1_2
截屏2022-03-06 下午7.14.58.png
String与Character
for c in "jack" { // c是Character类型
print(c)
}
var str = "jack"
// c是Character类型
var c = str[str.startIndex]
String与NSString
String与NSString之间可以随时随地桥接转换
如果你觉得String的API过于复杂难用,可以考虑将String转为NSString
var str1:String = "Jack"
var str2:NSString = "rose"
var str3 = str1 as NSString
var str4 = str2 as String
var str5 = str3.subString(with:NSRange(location:0, length:2))
print(str5) // ja
网友评论