Get nth character of a string in Swift programming language

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

    No indexing using integers, only using String.Index. Mostly with linear complexity. You can also create ranges from String.Index and get substrings using them.

    Swift 3.0

    let firstChar = someString[someString.startIndex]
    let lastChar = someString[someString.index(before: someString.endIndex)]
    let charAtIndex = someString[someString.index(someString.startIndex, offsetBy: 10)]
    
    let range = someString.startIndex..

    Swift 2.x

    let firstChar = someString[someString.startIndex]
    let lastChar = someString[someString.endIndex.predecessor()]
    let charAtIndex = someString[someString.startIndex.advanceBy(10)]
    
    let range = someString.startIndex..

    Note that you can't ever use an index (or range) created from one string to another string

    let index10 = someString.startIndex.advanceBy(10)
    
    //will compile
    //sometimes it will work but sometimes it will crash or result in undefined behaviour
    let charFromAnotherString = anotherString[index10]
    

提交回复
热议问题