Swift 字符串数字下标索引字符

本文介绍了一种在Swift中通过扩展来实现字符串字符和子字符串索引的方法。使用这种方法可以更方便地获取字符串中的特定字符或者子串,适用于需要频繁访问字符串内部元素的应用场景。

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

使用下标进行字符串字符索引

extension String{ 
    subscript(index:Int)->Character?{ 
    return self[self.characters.startIndex.advancedBy(index)] 
    } 
} 
extension String{ 
    subscript(index:Int)->String?{ 
        get{ 
            if index<0 || index>=self.characters.count{ 
                return nil
            } 
            return String(self[self.characters.startIndex.advancedBy(index)]) 
        }
        set(newValue){
            self.replaceRange(self.characters.startIndex.advancedBy(index)..<self.characters.startIndex.advancedBy(index+1),with:newValue!)
        }
    }
}

s.substring(0,11)
R13:String?=helloswifts[0]R14: Character? = “h”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值