1.移除一段特定的字符串
var str = "Hello word!"
let range = str.index(str.startIndex, offsetBy: 5)..<str.endIndex
str.removeSubrange(range)
print(str)
2.插入一个字符串
var str = "Hello!"
str.insert(contentsOf:"world", at: str.index(before: str.endIndex))
print(str)
3.替换字符串
func replace(of: String, with: String) -> String {
return self.replacingOccurrences(of: of, with: with)
}
let greeting = "Hello,world"
let str = greeting.replace(of: "world", with: "jesse")
print(str)
4.给String类添加下标脚本,支持索引访问(写在String类扩展里)
extension String
{
subscript(start:Int, length:Int) -> String
{
get{
let index1 = self.index(self.startIndex, offsetBy: start)
let index2 = self.index(index1, offsetBy: length)
return String(self[index1..<index2])
}
set{
let tmp = self
var s = ""
var e = ""
for (idx, item) in tmp.enumerated() {
if(idx < start)
{
s += "\(item)"
}
if(idx >= start + length)
{
e += "\(item)"
}
}
self = s + newValue + e
}
}
subscript(index:Int) -> String
{
get{
return String(self[self.index(self.startIndex, offsetBy: index)])
}
set{
let tmp = self
self = ""
for (idx, item) in tmp.enumerated() {
if idx == index {
self += "\(newValue)"
}else{
self += "\(item)"
}
}
}
}
}
使用案例
var greeting = "Hello, world!"
let subStr = greeting[2,3]
print(subStr)
greeting[2,3] = "222"
print(greeting)
print(greeting[3])
5.多行字面量:使用三个双引号(""")包裹
let str = """
12345
234567
3456789
"""
print(str)
打印结果
12345
234567
3456789
6.字符串切割(拆分)
let str = "Hello,world"
print(str.split(separator: ","))
7.判断字符串是否是整数(写在类扩展中)
func isPureInt() -> Bool {
let scan = Scanner(string: self)
var val = 0
let boolValue = scan.scanInt(&val) && scan.isAtEnd
return boolValue
}
使用案例
let str = "Hello,world"
print(str.isPureInt())
let str1 = "123"
print(str1.isPureInt())
|