Get nth character of a string in Swift programming language

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

    As an aside note, there are a few functions applyable directly to the Character-chain representation of a String, like this:

    var string = "Hello, playground"
    let firstCharacter = string.characters.first // returns "H"
    let lastCharacter = string.characters.last // returns "d"
    

    The result is of type Character, but you can cast it to a String.

    Or this:

    let reversedString = String(string.characters.reverse())
    // returns "dnuorgyalp ,olleH" 
    

    :-)

提交回复
热议问题