1. 程式人生 > >Swift 字串數字下標索引字元

Swift 字串數字下標索引字元

使用下標進行字串字元索引

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”