-
-
Save fitomad/dc4d822b1ec6234af16f86cb7b546f5f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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