Skip to content

Instantly share code, notes, and snippets.

@fitomad
Last active April 19, 2018 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fitomad/dc4d822b1ec6234af16f86cb7b546f5f to your computer and use it in GitHub Desktop.
Save fitomad/dc4d822b1ec6234af16f86cb7b546f5f to your computer and use it in GitHub Desktop.
import Foundation
var texto: String = "En un lugar de la Mencha"
//
// Con NSString. Necesitamos el framework Foundation
//
let correccion: String = texto.replacingOccurrences(of: "Mencha", with: "Mancha")
print("1. \(correccion)")
//
// Con String
//
// Creamos el índice de inicio.
// Lo situamos en la M de Mencha
let index_start: String.Index = texto.index(of: "M")!
// Creamos el índice final.
//Se situa 5 posiciones a la derecha desde el índice de inicio
let index_end: String.Index = texto.index(index_start, offsetBy: 5)
// Reemplazamos el rango entre los índices con otro texto
texto.replaceSubrange(index_start...index_end, with: "Comarca Manchega")
print("2. \(texto)")
//
// Otra forma de obtener el Range (rango de los índices)
// La función `range(of:)` devuelve un `Range`
//
if let range: Range = texto.range(of: "Comarca Manchega")
{
texto.replaceSubrange(range, with: "Mancha")
print("3. \(texto)")
}
/*
1. En un lugar de la Mancha
2. En un lugar de la Comarca Manchega
3. En un lugar de la Mancha
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment