Get nth character of a string in Swift programming language

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

    Swift 4

    let str = "My String"
    

    String at index

    let index = str.index(str.startIndex, offsetBy: 3)
    String(str[index])    // "S"
    

    Substring

    let startIndex = str.index(str.startIndex, offsetBy: 3)
    let endIndex = str.index(str.startIndex, offsetBy: 7)
    String(str[startIndex...endIndex])     // "Strin"
    

    First n chars

    let startIndex = str.index(str.startIndex, offsetBy: 3)
    String(str[..

    Last n chars

    let startIndex = str.index(str.startIndex, offsetBy: 3)
    String(str[startIndex...])    // "String"
    

    Swift 2 and 3

    str = "My String"
    

    **String At Index **

    Swift 2

    let charAtIndex = String(str[str.startIndex.advancedBy(3)])  // charAtIndex = "S"
    

    Swift 3

    str[str.index(str.startIndex, offsetBy: 3)]
    

    SubString fromIndex toIndex

    Swift 2

    let subStr = str[str.startIndex.advancedBy(3)...str.startIndex.advancedBy(7)] // subStr = "Strin"
    

    Swift 3

    str[str.index(str.startIndex, offsetBy: 3)...str.index(str.startIndex, offsetBy: 7)]
    

    First n chars

    let first2Chars = String(str.characters.prefix(2)) // first2Chars = "My"
    

    Last n chars

    let last3Chars = String(str.characters.suffix(3)) // last3Chars = "ing"
    

提交回复
热议问题