Eliminar el último carácter de la cadena. Lenguaje rápido


¿Cómo puedo eliminar el último carácter de la variable de cadena usando Swift? No puedo encontrarlo en la documentación.

Aquí está el ejemplo completo:

var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
Author: Konstantin Cherkasov, 2014-06-09

18 answers

Swift 4.0

var str = "Hello, World"                           // "Hello, World"
str.dropLast()                                     // "Hello, Worl" (non-modifying)
str                                                // "Hello, World"
String(str.dropLast())                             // "Hello, Worl"

str.remove(at: str.index(before: str.endIndex))    // "d"
str                                                // "Hello, Worl" (modifying)

Swift 3.0

Las APIs se han vuelto un poco más swifty , y como resultado la extensión Foundation ha cambiado un poco:

var name: String = "Dolphin"
var truncated = name.substring(to: name.index(before: name.endIndex))
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

O la versión in situ:

var name: String = "Dolphin"
name.remove(at: name.index(before: name.endIndex))
print(name)      // "Dolphi"

Gracias Zmey, Rob Allen!

Swift 2.0 + Way

Hay algunas maneras de lograr esto:

A través de la extensión Foundation, a pesar de no ser parte de Swift biblioteca:

var name: String = "Dolphin"
var truncated = name.substringToIndex(name.endIndex.predecessor())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Utilizando el método removeRange() (que altera el name):

var name: String = "Dolphin"    
name.removeAtIndex(name.endIndex.predecessor())
print(name) // "Dolphi"

Usando la función dropLast():

var name: String = "Dolphin"
var truncated = String(name.characters.dropLast())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Cuerda Vieja.Index (Xcode 6 Beta 4 +) Way

Dado que los tipos String en Swift tienen como objetivo proporcionar un excelente soporte UTF-8, ya no puede acceder a índices/rangos/subcadenas de caracteres utilizando tipos Int. En su lugar, se utiliza String.Index:

let name: String = "Dolphin"
let stringLength = count(name) // Since swift1.2 `countElements` became `count`
let substringIndex = stringLength - 1
name.substringToIndex(advance(name.startIndex, substringIndex)) // "Dolphi"

Alternativamente (para un ejemplo más práctico, pero menos educativo) puede usar endIndex:

let name: String = "Dolphin"
name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"

Nota: Encontré esto para ser un gran punto de partida para la comprensión String.Index

Antiguo (pre-Beta 4) Camino

Simplemente puede usar la función substringToIndex(), siempre que sea una menos que la longitud de la String:

let name: String = "Dolphin"
name.substringToIndex(countElements(name) - 1) // "Dolphi"
 455
Author: Craig Otis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-31 00:26:33

La función global dropLast() funciona en secuencias y por lo tanto en Cadenas:

var expression  = "45+22"
expression = dropLast(expression)  // "45+2"

// in Swift 2.0 (according to cromanelli's comment below)
expression = String(expression.characters.dropLast())
 88
Author: gui_dos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-30 14:04:45

Swift 4:

let choppedString = String(theString.dropLast())

En Swift 2, haz esto:

let choppedString = String(theString.characters.dropLast())

Recomiendo este enlace para obtener una comprensión de las cadenas Swift.

 66
Author: jrc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-28 09:08:57

Esta es una cadena Forma de extensión:

extension String {

    func removeCharsFromEnd(count_:Int) -> String {
        let stringLength = count(self)

        let substringIndex = (stringLength < count_) ? 0 : stringLength - count_

        return self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

Para versiones de Swift anteriores a 1.2:

...
let stringLength = countElements(self)
...

Uso:

var str_1 = "Maxim"
println("output: \(str_1.removeCharsFromEnd(1))") // "Maxi"
println("output: \(str_1.removeCharsFromEnd(3))") // "Ma"
println("output: \(str_1.removeCharsFromEnd(8))") // ""

Referencia:

Las extensiones añaden una nueva funcionalidad a una clase, estructura o tipo de enumeración existente. Esto incluye la capacidad de extender tipos para los que no tiene acceso al código fuente original (conocido como modelado retroactivo). Las extensiones son similares a las categorías en Objective-C. (A diferencia de las categorías Objective-C, las extensiones Swift no tienen nombres.)

Véase DOCUMENTOS

 8
Author: Maxim Shoustin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-19 23:05:58

Utilice la función removeAtIndex(i: String.Index) -> Character:

var s = "abc"    
s.removeAtIndex(s.endIndex.predecessor())  // "ab"
 6
Author: Anton Serkov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-01 03:33:13

La forma más fácil de recortar el último carácter de la cadena es:

title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]
 5
Author: Kunal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-31 11:17:32

Swift 4

var welcome = "Hello World!"
welcome = String(welcome[..<welcome.index(before:welcome.endIndex)])

O

welcome.remove(at: welcome.index(before: welcome.endIndex))

O

welcome = String(welcome.dropLast())
 5
Author: Carien van Zyl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-26 13:53:22
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor())  // "ab"
 2
Author: Channing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-22 03:58:30
var str = "Hello, playground"

extension String {
    var stringByDeletingLastCharacter: String {
        return dropLast(self)
    }
}

println(str.stringByDeletingLastCharacter)   // "Hello, playgroun"
 2
Author: Leo Dabus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-01 03:31:29

Respuesta corta (válida a partir de 2015-04-16): removeAtIndex(myString.endIndex.predecessor())

Ejemplo:

var howToBeHappy = "Practice compassion, attention and gratitude. And smile!!"
howToBeHappy.removeAtIndex(howToBeHappy.endIndex.predecessor())
println(howToBeHappy)
// "Practice compassion, attention and gratitude. And smile!"

Meta:

El lenguaje continúa su rápida evolución, haciendo que la semivida para muchas respuestas anteriormente buenas S. O. sea peligrosamente breve. Siempre es mejor aprender el idioma y consultar la documentación real .

 2
Author: cweekly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-20 10:20:29

Con el nuevo tipo de Subcadena uso:

Swift 4:

var before: String = "Hello world!"
var lastCharIndex: Int = before.endIndex
var after:String = String(before[..<lastCharIndex])
print(after) // Hello world

Camino más corto:

var before: String = "Hello world!"
after = String(before[..<before.endIndex])
print(after) // Hello world
 2
Author: Jorge Ramírez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-20 09:00:30

Utilice la función advance(startIndex, endIndex):

var str = "45+22"
str = str.substringToIndex(advance(str.startIndex, countElements(str) - 1))
 1
Author: Chen Rui,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-01 03:32:43

Una categoría swift que está mutando:

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

Uso:

var myString = "abcd"
myString.removeCharsFromEnd(2)
println(myString) // "ab"
 1
Author: Sunkas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-20 10:01:05

De otra manera Si desea eliminar uno o más de un carácter del final.

var myStr = "Hello World!"
myStr = (myStr as NSString).substringToIndex((myStr as NSString).length-XX)

Donde XX es el número de caracteres que desea eliminar.

 1
Author: Kaiusee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-27 19:14:43

Swift 3 (según los documentos ) 20 de noviembre de 2016

let range = expression.index(expression.endIndex, offsetBy: -numberOfCharactersToRemove)..<expression.endIndex
expression.removeSubrange(range)
 1
Author: narco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-20 15:50:13

Recomendaría usar NSString para cadenas que desea manipular. En realidad, ahora que lo pienso como un desarrollador, nunca me he encontrado con un problema con NSString que Swift String resolvería... Entiendo las sutilezas. Pero aún no tengo una necesidad real de ellos.

var foo = someSwiftString as NSString

O

var foo = "Foo" as NSString

O

var foo: NSString = "blah"

Y entonces todo el mundo de operaciones simples de cadena NSString está abierto para usted.

Como respuesta a la pregunta

// check bounds before you do this, e.g. foo.length > 0
// Note shortFoo is of type NSString
var shortFoo = foo.substringToIndex(foo.length-1)
 0
Author: n13,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-04 11:14:02

Complementario al código anterior Quería eliminar el principio de la cadena y no pude encontrar una referencia en ningún lugar. Así es como lo hice:

            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

Esto recorta 17 caracteres desde el principio de la cadena (la longitud total de la cadena es 67 avanzamos -50 desde el final y ahí lo tienes.

 0
Author: Sophman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-09 17:58:17

La función dropLast() elimina el último elemento de la cadena.

var expression = "45+22"
expression = expression.dropLast()
 0
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-08 17:18:12