8
votes

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.

8
When you pass nil as the range, of course it will replace all the & characters as you are using stringByReplacingOccurrencesOfString.Kyle Emmanuel
I get that, I just wanted to tell that I got that working.Den3243

8 Answers

18
votes

You can try this:

var s = "123456"

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

s2 // "a23456"
19
votes

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"
}
4
votes
let range = Range(start: query.startIndex, end: query.startIndex.successor())
query.replaceRange(range, with: "?")

or shorter

let s = query.startIndex
query.replaceRange(s...s, with: "?")

This is a bit different from Objective-C - but we will get used to it I guess ;-).

If you are uncomfortable with this, you can always drop back to the old NSString APIs:

let newQuery = (query as NSString).stringByReplacingCharactersInRange(
  NSMakeRange(0,1), withString: "?") // as String not necessary
1
votes

In Swift 4.0

let inputString = "!Hello"
let outputString = String(inputString.dropFirst())

Answer

outputString = "Hello"
0
votes

The problem is that you are passing an NSRange value, where a Range object is expected. When using Swift strings, you have to use

Range<String.Index>(start: str.startIndex, end: advance(str.startIndex, 1))
0
votes

In Swift 2.0 you can do something like this:-

let inputString = "!Hello"
let outputString = String(inputString.characters.dropFirst())

//Answer
outputString = "Hello"
0
votes

Swift 4.0

extension String
{
    func replace_fromStart(str:String , endIndex:Int , With:String) -> String {
        var strReplaced = str ;
        let start = str.startIndex;
        let end = str.index(str.startIndex, offsetBy: endIndex);
        strReplaced = str.replacingCharacters(in: start..<end, with: With) ;
        return strReplaced;
    }
}

use it any where

MY_String.replace_fromStart(str: MY_String, endIndex: 10, With: "**********")
0
votes

Another answer

Use suffix

var s = "1234567"
var transform = "?" + s.suffix(max(s.count - 1, 0))
transform // "?234567"