Get nth character of a string in Swift programming language

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

    Swift 4.2

    This answer is ideal because it extends String and all of its Subsequences (Substring) in one extension

    public extension StringProtocol {
        
        public subscript (i: Int) -> Element {
            return self[index(startIndex, offsetBy: i)]
        }
    
        public subscript (bounds: CountableClosedRange) -> SubSequence {
            let start = index(startIndex, offsetBy: bounds.lowerBound)
            let end = index(startIndex, offsetBy: bounds.upperBound)
            return self[start...end]
        }
        
        public subscript (bounds: CountableRange) -> SubSequence {
            let start = index(startIndex, offsetBy: bounds.lowerBound)
            let end = index(startIndex, offsetBy: bounds.upperBound)
            return self[start..) -> SubSequence {
            let end = index(startIndex, offsetBy: bounds.upperBound)
            return self[startIndex..) -> SubSequence {
            let end = index(startIndex, offsetBy: bounds.upperBound)
            return self[startIndex...end]
        }
        
        public subscript (bounds: CountablePartialRangeFrom) -> SubSequence {
            let start = index(startIndex, offsetBy: bounds.lowerBound)
            return self[start..

    Usage

    var str = "Hello, playground"
    
    print(str[5...][...5][0])
    // Prints ","
    

提交回复
热议问题