Remove last character from string. Swift language

前端 未结 22 1677
Happy的楠姐
Happy的楠姐 2020-11-30 17:33

How can I remove last character from String variable using Swift? Can\'t find it in documentation.

Here is full example:

var expression = \"45+22\"
e         


        
相关标签:
22条回答
  • 2020-11-30 17:58

    complimentary to the above code I wanted to remove the beginning of the string and could not find a reference anywhere. Here is how I did it:

    var mac = peripheral.identifier.description
    let range = mac.startIndex..<mac.endIndex.advancedBy(-50)
    mac.removeRange(range)  // trim 17 characters from the beginning
    let txPower = peripheral.advertisements.txPower?.description
    

    This trims 17 characters from the beginning of the string (he total string length is 67 we advance -50 from the end and there you have it.

    0 讨论(0)
  • 2020-11-30 17:59

    The dropLast() function removes the last element of the string.

    var expression = "45+22"
    expression = expression.dropLast()
    
    0 讨论(0)
  • 2020-11-30 18:00

    The global dropLast() function works on sequences and therefore on Strings:

    var expression  = "45+22"
    expression = dropLast(expression)  // "45+2"
    
    // in Swift 2.0 (according to cromanelli's comment below)
    expression = String(expression.characters.dropLast())
    
    0 讨论(0)
  • 2020-11-30 18:00

    Swift 3 (according to the docs) 20th Nov 2016

    let range = expression.index(expression.endIndex, offsetBy: -numberOfCharactersToRemove)..<expression.endIndex
    expression.removeSubrange(range)
    
    0 讨论(0)
  • 2020-11-30 18:01
    var str = "Hello, playground"
    
    extension String {
        var stringByDeletingLastCharacter: String {
            return dropLast(self)
        }
    }
    
    println(str.stringByDeletingLastCharacter)   // "Hello, playgroun"
    
    0 讨论(0)
  • 2020-11-30 18:02

    A swift category that's mutating:

    extension String {
        mutating func removeCharsFromEnd(removeCount:Int)
        {
            let stringLength = count(self)
            let substringIndex = max(0, stringLength - removeCount)
            self = self.substringToIndex(advance(self.startIndex, substringIndex))
        }
    }
    

    Use:

    var myString = "abcd"
    myString.removeCharsFromEnd(2)
    println(myString) // "ab"
    
    0 讨论(0)
提交回复
热议问题