Sto cercando un modo per sostituire i personaggi in Swift String.
Esempio: "Questa è la mia stringa"
Vorrei sostituire "" con "+" per ottenere "This + is + my + string".
Come posso raggiungere questo obiettivo?
Sto cercando un modo per sostituire i personaggi in Swift String.
Esempio: "Questa è la mia stringa"
Vorrei sostituire "" con "+" per ottenere "This + is + my + string".
Come posso raggiungere questo obiettivo?
Risposte:
Questa risposta è stata aggiornata per Swift 4 e 5 . Se stai ancora utilizzando Swift 1, 2 o 3, consulta la cronologia delle revisioni.
Hai un paio di opzioni. Puoi fare come suggerito e usare @jaumardreplacingOccurrences()
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
E come notato da @cprcrack di seguito, i parametri optionse rangesono facoltativi, quindi se non si desidera specificare le opzioni di confronto delle stringhe o un intervallo in cui effettuare la sostituzione, è necessario solo quanto segue.
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")
Oppure, se i dati sono in un formato specifico come questo, in cui si stanno semplicemente sostituendo i caratteri di separazione, è possibile utilizzare components()per suddividere la stringa in e l'array, quindi è possibile utilizzare la join()funzione per rimetterli insieme a un separatore specificato .
let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")
O se stai cercando una soluzione più Swifty che non utilizza l'API di NSString, puoi usarla.
let aString = "Some search text"
let replaced = String(aString.map {
$0 == " " ? "+" : $0
})
"x86_64"e la nuova mappatura assomiglia a"Optional([\"x\", \"8\", \"6\", \"_\", \"6\", \"4\"])"
stringByReplacingOccurrencesOfStringdi Swift 2, devi import Foundationessere in grado di utilizzare quel metodo.
Puoi usare questo:
let s = "This is my string"
let modified = s.replace(" ", withString:"+")
Se aggiungi questo metodo di estensione in qualsiasi punto del codice:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
}
Swift 3:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
}
Soluzione Swift 3, Swift 4, Swift 5
let exampleString = "Example string"
//Solution suggested above in Swift 3.0
let stringToArray = exampleString.components(separatedBy: " ")
let stringFromArray = stringToArray.joined(separator: "+")
//Swiftiest solution
let swiftyString = exampleString.replacingOccurrences(of: " ", with: "+")
Sto usando questa estensione:
extension String {
func replaceCharacters(characters: String, toSeparator: String) -> String {
let characterSet = NSCharacterSet(charactersInString: characters)
let components = self.componentsSeparatedByCharactersInSet(characterSet)
let result = components.joinWithSeparator("")
return result
}
func wipeCharacters(characters: String) -> String {
return self.replaceCharacters(characters, toSeparator: "")
}
}
Uso:
let token = "<34353 43434>"
token.replaceCharacters("< >", toString:"+")
Una soluzione Swift 3 sulla falsariga di Sunkas:
extension String {
mutating func replace(_ originalString:String, with newString:String) {
self = self.replacingOccurrences(of: originalString, with: newString)
}
}
Uso:
var string = "foo!"
string.replace("!", with: "?")
print(string)
Produzione:
foo?
Una categoria che modifica una stringa mutabile esistente:
extension String
{
mutating func replace(originalString:String, withString newString:String)
{
let replacedString = self.stringByReplacingOccurrencesOfString(originalString, withString: newString, options: nil, range: nil)
self = replacedString
}
}
Uso:
name.replace(" ", withString: "+")
Soluzione Swift 3 basata sulla risposta di Ramis :
extension String {
func withReplacedCharacters(_ characters: String, by separator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
return components(separatedBy: characterSet).joined(separator: separator)
}
}
Ho provato a trovare un nome di funzione appropriato secondo la convenzione di denominazione di Swift 3.
Meno mi è successo, voglio solo cambiare (una parola o un carattere) in String
Quindi ho usato il Dictionary
extension String{
func replace(_ dictionary: [String: String]) -> String{
var result = String()
var i = -1
for (of , with): (String, String)in dictionary{
i += 1
if i<1{
result = self.replacingOccurrences(of: of, with: with)
}else{
result = result.replacingOccurrences(of: of, with: with)
}
}
return result
}
}
uso
let mobile = "+1 (800) 444-9999"
let dictionary = ["+": "00", " ": "", "(": "", ")": "", "-": ""]
let mobileResult = mobile.replace(dictionary)
print(mobileResult) // 001800444999
replace
var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)
replacingOccurrencesin String?
Penso che Regex sia il modo più flessibile e solido:
var str = "This is my string"
let regex = try! NSRegularExpression(pattern: " ", options: [])
let output = regex.stringByReplacingMatchesInString(
str,
options: [],
range: NSRange(location: 0, length: str.characters.count),
withTemplate: "+"
)
// output: "This+is+my+string"
Estensione rapida:
extension String {
func stringByReplacing(replaceStrings set: [String], with: String) -> String {
var stringObject = self
for string in set {
stringObject = self.stringByReplacingOccurrencesOfString(string, withString: with)
}
return stringObject
}
}
Continua e usalo come let replacedString = yorString.stringByReplacing(replaceStrings: [" ","?","."], with: "+")
La velocità della funzione è qualcosa di cui difficilmente posso essere orgoglioso, ma puoi passare un array di Stringin un passaggio per effettuare più di una sostituzione.
Ecco l'esempio per Swift 3:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
Xcode 11 • Swift 5.1
Il metodo mutante di StringProtocol replacingOccurrencespuò essere implementato come segue:
extension RangeReplaceableCollection where Self: StringProtocol {
mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<String.Index>? = nil) {
self = .init(replacingOccurrences(of: target, with: replacement, options: options, range: searchRange))
}
}
var name = "This is my string"
name.replaceOccurrences(of: " ", with: "+")
print(name) // "This+is+my+string\n"
Se non vuoi usare i NSStringmetodi Objective-C , puoi semplicemente usare splite join:
var string = "This is my string"
string = join("+", split(string, isSeparator: { $0 == " " }))
split(string, isSeparator: { $0 == " " })restituisce una matrice di stringhe ( ["This", "is", "my", "string"]).
joinunisce questi elementi con +, con conseguente uscita desiderato "This+is+my+string".
Ho implementato questa funzione molto semplice:
func convap (text : String) -> String {
return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}
Quindi puoi scrivere:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')
puoi provare questo:
let newString = test.stringByReplacingOccurrencesOfString ("", withString: "+", opzioni: zero, intervallo: zero)
Ecco un'estensione per un metodo di sostituzione delle occorrenze sul posto String, che non ha una copia non necessaria e fa tutto sul posto:
extension String {
mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
var range: Range<Index>?
repeat {
range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..<self.endIndex }, locale: locale)
if let range = range {
self.replaceSubrange(range, with: replacement)
}
} while range != nil
}
}
(La firma del metodo imita anche la firma del String.replacingOccurrences()metodo integrato )
Può essere utilizzato nel modo seguente:
var string = "this is a string"
string.replaceOccurrences(of: " ", with: "_")
print(string) // "this_is_a_string"