Get nth character of a string in Swift programming language

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

    Swift 2.0 as of Xcode 7 GM Seed

    var text = "Hello, world!"
    
    let firstChar = text[text.startIndex.advancedBy(0)] // "H"
    

    For the nth character, replace 0 with n-1.

    Edit: Swift 3.0

    text[text.index(text.startIndex, offsetBy: 0)]
    


    n.b. there are simpler ways of grabbing certain characters in the string

    e.g. let firstChar = text.characters.first

提交回复
热议问题