Get nth character of a string in Swift programming language

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

    Swift 5.2

    let str = "abcdef"
    str[1 ..< 3] // returns "bc"
    str[5] // returns "f"
    str[80] // returns ""
    str.substring(fromIndex: 3) // returns "def"
    str.substring(toIndex: str.length - 2) // returns "abcd"
    

    You will need to add this String extension to your project (it's fully tested):

    extension String {
    
        var length: Int {
            return count
        }
    
        subscript (i: Int) -> String {
            return self[i ..< i + 1]
        }
    
        func substring(fromIndex: Int) -> String {
            return self[min(fromIndex, length) ..< length]
        }
    
        func substring(toIndex: Int) -> String {
            return self[0 ..< max(0, toIndex)]
        }
    
        subscript (r: Range) -> String {
            let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
                                                upper: min(length, max(0, r.upperBound))))
            let start = index(startIndex, offsetBy: range.lowerBound)
            let end = index(start, offsetBy: range.upperBound - range.lowerBound)
            return String(self[start ..< end])
        }
    }
    

    Even though Swift always had out of the box solution to this problem (without String extension, which I provided below), I still would strongly recommend using the extension. Why? Because it saved me tens of hours of painful migration from early versions of Swift, where String's syntax was changing almost every release, but all I needed to do was to update the extension's implementation as opposed to refactoring the entire project. Make your choice.

    let str = "Hello, world!"
    let index = str.index(str.startIndex, offsetBy: 4)
    str[index] // returns Character 'o'
    
    let endIndex = str.index(str.endIndex, offsetBy:-2)
    str[index ..< endIndex] // returns String "o, worl"
    
    String(str.suffix(from: index)) // returns String "o, world!"
    String(str.prefix(upTo: index)) // returns String "Hell"
    

提交回复
热议问题