Get nth character of a string in Swift programming language

后端 未结 30 2506
一整个雨季
一整个雨季 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:40

    Swift 3

    extension String {
    
        public func charAt(_ i: Int) -> Character {
            return self[self.characters.index(self.startIndex, offsetBy: i)]
        }
    
        public subscript (i: Int) -> String {
            return String(self.charAt(i) as Character)
        }
    
        public subscript (r: Range) -> String {
            return substring(with: self.characters.index(self.startIndex, offsetBy: r.lowerBound)..) -> String {
            return substring(with: self.characters.index(self.startIndex, offsetBy: r.lowerBound)..

    Usage

    let str = "Hello World"
    let sub = str[0...4]
    

    Helpful Programming Tips and Tricks (written by me)

提交回复
热议问题