Get nth character of a string in Swift programming language

后端 未结 30 2031
一整个雨季
一整个雨季 2020-11-22 01:26

How can I get the nth character of a string? I tried bracket([]) accessor with no luck.

var string = \"Hello, world!\"

var firstChar = string[         


        
30条回答
  •  别那么骄傲
    2020-11-22 01:58

    Swift 3: another solution (tested in playground)

    extension String {
        func substr(_ start:Int, length:Int=0) -> String? {
            guard start > -1 else {
                return nil
            }
    
            let count = self.characters.count - 1
    
            guard start <= count else {
                return nil
            }
    
            let startOffset = max(0, start)
            let endOffset = length > 0 ? min(count, startOffset + length - 1) : count
    
            return self[self.index(self.startIndex, offsetBy: startOffset)...self.index(self.startIndex, offsetBy: endOffset)]
        }
    }
    

    Usage:

    let txt = "12345"
    
    txt.substr(-1) //nil
    txt.substr(0) //"12345"
    txt.substr(0, length: 0) //"12345"
    txt.substr(1) //"2345"
    txt.substr(2) //"345"
    txt.substr(3) //"45"
    txt.substr(4) //"5"
    txt.substr(6) //nil
    txt.substr(0, length: 1) //"1"
    txt.substr(1, length: 1) //"2"
    txt.substr(2, length: 1) //"3"
    txt.substr(3, length: 1) //"4"
    txt.substr(3, length: 2) //"45"
    txt.substr(3, length: 3) //"45"
    txt.substr(4, length: 1) //"5"
    txt.substr(4, length: 2) //"5"
    txt.substr(5, length: 1) //nil
    txt.substr(5, length: -1) //nil
    txt.substr(-1, length: -1) //nil
    

提交回复
热议问题