swift - 字符串的安插、删除和替换

本文介绍了Swift中如何使用内置方法对字符串进行插入、删除和替换等操作。通过实例演示了splice、insert、removeAtIndex、removeRange及replaceRange等方法的具体用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对应可变字符串可以插入、删除和替换,String提供了几个方法可以帮助实现这些操作。这些方法如下:

splice(_:atIndex:)。在索引位置插入字符串。
insert(_:atIndex:)。在索引位置插入字符。
removeAtIndex(_:)。在索引位置删除字符。
removeRange(_:)。删除指定范围内的字符串。
replaceRange(_:,with: String) 。使用字符串或字符替换指定范围内的字符串。

代码:

var str ="Swift"
print("原始字符串:\(str)")

str.splice("Objective-Cand ".characters, atIndex: str.startIndex)
print("插入字符串后:\(str)")

str.insert(".",atIndex: str.endIndex)    
print("插入.字符后:\(str)")

str.removeAtIndex(str.endIndex.predecessor())
print("删除.字符后:\(str)")

var startIndex =str.startIndex           
var endIndex =advance(startIndex, 9)     
var range =startIndex...endIndex     

str.removeRange(range)                
print("删除范围后:\(str)")

startIndex =str.startIndex
endIndex =advance(startIndex, 0)
range =startIndex...endIndex      

str.replaceRange(range,with: "C++")  
print("替换范围后:\(str)")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值