Swift: replace character in string - without stringByReplacingOccurrencesOfString

Ok let's say i have Stringlike

let myString = "my string: hello"

and I want to replace ":" with ",". I got to this:

let characters = map(Array(myString), {$0 == ":" ? "," : $0})

Returns a MapCollectionView<Array<Character>, Character>. Is there an easy way to convert this back to String?

+4
source share
3 answers

How about this? Combine all characters with a string by “decreasing” them using the + Operator:

let str = Array(characters).reduce("", combine: +)
println(str)
// Output: my string, hello

Update: an alternative (perhaps more enjoyable) solution:

var str = ""
str.extend(characters)

Using extend(), string replacement can be performed without intermediate Array:

let myString = "my string: hello" as String
var myNewString = ""
myNewString.extend(map(myString.generate(), {$0 == ":" ? "," : $0} ))
+4
source

Thanks to Martin R's answer, I reduced my code to:

let myString = "my string: hello" as String
let myNewString = Array(myString).reduce("") { $0 + (String($1) == ":" ? "," : String($1)) }

Update

- Xcode 6.2, :

let myString = "my string: hello"
let result = String(map(Array(myString)) {$0 == ":" ? "," : $0})

// Output: my string, hello
+2

( ), :

var aString = "Replace the letter e with *"

import Foundation
while let range: Range<String.Index> =  aString.rangeOfString("e") {
    aString.replaceRange(range, with: "*")
}

Xcode 7.0.1

0
source

Source: https://habr.com/ru/post/1546838/


All Articles