Random replace using Swift
Similarly as in Replace specific characters in string, you can map each character, and combine the result to a string. But now you have to keep track of the (remaining) numbers of non-space characters, and the (remaining) numbers of characters that should be displayed. For each (non-space) character it is randomly decided whether to display (keep) it or to replace it by an underscore.
let s = "Hello playground"
let factor = 0.25
var n = s.filter({ $0 != " " }).count // # of non-space characters
var m = lrint(factor * Double(n)) // # of characters to display
let t = String(s.map { c -> Character in
if c == " " {
// Preserve space
return " "
} else if Int.random(in: 0..<n) < m {
// Keep
m -= 1
n -= 1
return c
} else {
// Replace
n -= 1
return "_"
}
})
print(t) // _e_l_ ______o_n_
Any way to replace characters on Swift String?
This answer has been updated for Swift 4 & 5. If you're still using Swift 1, 2 or 3 see the revision history.
You have a couple of options. You can do as @jaumard suggested and use replacingOccurrences()
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
And as noted by @cprcrack below, the options
and range
parameters are optional, so if you don't want to specify string comparison options or a range to do the replacement within, you only need the following.
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")
Or, if the data is in a specific format like this, where you're just replacing separation characters, you can use components()
to break the string into and array, and then you can use the join()
function to put them back to together with a specified separator.
let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")
Or if you're looking for a more Swifty solution that doesn't utilize API from NSString, you could use this.
let aString = "Some search text"
let replaced = String(aString.map {
$0 == " " ? "+" : $0
})
How can I change random string inside link?
Just parse the URL and replace the host and path with your desired string!
let link = "applewebdata://DA4343F3-A092-4BF1-B76F-7FC7F128C7D9/?q=se%c3%a7im+yasaklar%c4%b1"
var url = URLComponents(string: link)!
url.host = "category"
url.path = "/user/"
print("\(url)") // applewebdata://category/user/?q=se%c3%a7im+yasaklar%c4%b1
Swift - Replace exact matching Characters / Words in String (not containing)
You just need to use replacingOccurences(of:with:options:)
and pass .regularExpression
to options
. You also need to pass a regex to of:
now instead of just passing the substring you want to replace. The correct regex here if \\bc\\b
, which matches a word boundary before and after c
ensuring that it's just the char c
you are matching and not a c
that's part of a word/expression.
let string = "c \\cdot c"
let replacingString = string.replacingOccurrences(of: "\\bc\\b", with: "2", options: .regularExpression)
print(replacingString) // "2 \\cdot 2"
Replace specific characters in string in Swift
If you want to replace all word characters, you can use the regularExpressions
input to the options
parameter of the same function you were using before, just change the specific String input to \\w
, which will match any word characters.
let str = "Hello World"
let replace = str.replacingOccurrences(of: "\\w", with: "_", options: .regularExpression) // "_____ _____"
Bear in mind that the \\w
won't replace other special characters either, so for an input of "Hello World!"
, it will produce "_____ _____!"
. If you want to replace every character but whitespaces, use \\S
.
let replace = str.replacingOccurrences(of: "\\S", with: "_", options: .regularExpression)
swift - using replaceRange() to change certain occurrences in a string
This is is what you want to do:
var animal = "elaphant"
if let range = animal.rangeOfString("a") {
animal.replaceRange(range, with: "e")
}
rangeOfString
will search for the first occurrence of the provided substring and if that substring can be found it will return a optional range otherwise it will return nil.
we need to unwrap the optional and the safest way is with an if let
statement so we assign our range to the constant range
.
The replaceRange
will do as it suggests, in this case we need animal
to be a var
.
Swift: Simple method to replace a single character in a String?
To replace the first character, you can do use String
concatenation with dropFirst()
:
var s = "hello world!"
s = "." + s.dropFirst()
print(s)
Result:
.hello world!
Note: This will not crash if the String
is empty; it will just create a String
with the replacement character.
Swift: replace character in string - without stringByReplacingOccurrencesOfString
What about this? Combine all characters to a string by "reducing" them with the +
operator:
let str = Array(characters).reduce("", combine: +)
println(str)
// Output: my string, hello
Update: An alternative (perhaps nicer) solution:
var str = ""
str.extend(characters)
Using extend()
, the string replacement could be done without an intermediate Array
:
let myString = "my string: hello" as String
var myNewString = ""
myNewString.extend(map(myString.generate(), {$0 == ":" ? "," : $0} ))
Related Topics
Programmatically Create an Nsviewcontroller Without an Xib in Swift 3
Swift Conditional Conformances with Generic Type
How to Prevent a Spacer to Make a VStack Greedly Grow Beyond Necessary
Build Error in Xcode on Cloud-Hosted MAC on VSts
How to Cast an @Binding in Swift
Need Detailed Explanation for Memoize Implementation in Swift (Wwdc 14, Session 404)
How to Get the Unicode Codepoint Represented by an Integer in Swift
Nsurlsessiondatadelegate Method Didreceivedata and Others Are Not Called
Is a Static Boolean a Reference Type in Swift
Realmswift + Multiple Predicate
Convert to Latest Swift Syntax' Breaks the Build Even When There Are No Changes
Add Skin Tone Modifier to an Emoji Programmatically
Ckcontainer.Discoverallidentities Always Fails
How to Create a Multiline Textfield in Swiftui? Like the Notes App
How to Have Arview and Arscnview Coexist