Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift replace first character in string

Tags:

ios

swift

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.

like image 897
Den3243 Avatar asked Aug 12 '15 23:08

Den3243


People also ask

How do I change the first character of a string in Swift?

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.

How do I remove the first character from a string in Swift 5?

Swift String dropFirst() The dropFirst() method removes the first character of the string.

How do I change occurrences in Swift?

The replacingOccurrences() method replaces each matching occurrence of the old character/text in the string with the new character/text.


2 Answers

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"
}
like image 122
Leo Dabus Avatar answered Oct 20 '22 00:10

Leo Dabus


You can try this:

var s = "123456"

let s2 = s.replacingCharacters(in: ...s.startIndex, with: "a")

s2 // "a23456"
like image 43
MirekE Avatar answered Oct 20 '22 01:10

MirekE