Get nth character of a string in Swift programming language

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

    Here's an extension you can use, working with Swift 3.1. A single index will return a Character, which seems intuitive when indexing a String, and a Range will return a String.

    extension String {
        subscript (i: Int) -> Character {
            return Array(self.characters)[i]
        }
        
        subscript (r: CountableClosedRange) -> String {
            return String(Array(self.characters)[r])
        }
        
        subscript (r: CountableRange) -> String {
            return self[r.lowerBound...r.upperBound-1]
        }
    }
    

    Some examples of the extension in action:

    let string = "Hello"
    
    let c1 = string[1]  // Character "e"
    let c2 = string[-1] // fatal error: Index out of range
    
    let r1 = string[1..<4] // String "ell"
    let r2 = string[1...4] // String "ello"
    let r3 = string[1...5] // fatal error: Array index is out of range
    


    n.b. You could add an additional method to the above extension to return a String with a single character if wanted:

    subscript (i: Int) -> String {
        return String(self[i])
    }
    

    Note that then you would have to explicitly specify the type you wanted when indexing the string:

    let c: Character = string[3] // Character "l"
    let s: String = string[0]    // String "H"
    

提交回复
热议问题