A very simple question, how do I replace the first character of a string. I'm probably doing something totally wrong, but I simply can't get it to work.
I have tried this: var query = url.query!.stringByReplacingOccurrencesOfString("&", withString: "?", options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, 1))
But it gives me the following error:
Cannot invoke 'stringByReplacingOccurrencesOfString' with an argument list of type '(String, withString: String, options: NSStringCompareOptions, range: NSRange)'
When I remove the NSMakeRange and change it to nil, it works, but it replaces all the &'s in the string.
When I remove the NSMakeRange and change it to nil, it works, but it replaces all the &'s in the string. When you pass nil as the range , of course it will replace all the & characters as you are using stringByReplacingOccurrencesOfString . I get that, I just wanted to tell that I got that working.
Swift String dropFirst() The dropFirst() method removes the first character of the string.
The replacingOccurrences() method replaces each matching occurrence of the old character/text in the string with the new character/text.
Swift 4 or later
let string = "&whatever"
let output = "?" + string.dropFirst()
mutating the string
var string = "&whatever"
if !string.isEmpty {
string.replaceSubrange(...string.startIndex, with: "?")
print(string) // "?whatever\n"
}
You can try this:
var s = "123456"
let s2 = s.replacingCharacters(in: ...s.startIndex, with: "a")
s2 // "a23456"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With