Get nth character of a string in Swift programming language

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

    I think that a fast answer for get the first character could be:

    let firstCharacter = aString[aString.startIndex]
    

    It's so much elegant and performance than:

    let firstCharacter = Array(aString.characters).first
    

    But.. if you want manipulate and do more operations with strings you could think create an extension..here is one extension with this approach, it's quite similar to that already posted here:

    extension String {
    var length : Int {
        return self.characters.count
    }
    
    subscript(integerIndex: Int) -> Character {
        let index = startIndex.advancedBy(integerIndex)
        return self[index]
    }
    
    subscript(integerRange: Range) -> String {
        let start = startIndex.advancedBy(integerRange.startIndex)
        let end = startIndex.advancedBy(integerRange.endIndex)
        let range = start..

    }

    BUT IT'S A TERRIBLE IDEA!!

    The extension below is horribly inefficient. Every time a string is accessed with an integer, an O(n) function to advance its starting index is run. Running a linear loop inside another linear loop means this for loop is accidentally O(n2) — as the length of the string increases, the time this loop takes increases quadratically.

    Instead of doing that you could use the characters's string collection.

提交回复
热议问题