Get nth character of a string in Swift programming language

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

    Swift 4

    String(Array(stringToIndex)[index]) 
    

    This is probably the best way of solving this problem one-time. You probably want to cast the String as an array first, and then cast the result as a String again. Otherwise, a Character will be returned instead of a String.

    Example String(Array("HelloThere")[1]) will return "e" as a String.

    (Array("HelloThere")[1] will return "e" as a Character.

    Swift does not allow Strings to be indexed like arrays, but this gets the job done, brute-force style.

提交回复
热议问题