Reputation: 161
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.
Upvotes: 9
Views: 22487
Reputation: 2632
Another answer
Use suffix
var s = "1234567"
var transform = "?" + s.suffix(max(s.count - 1, 0))
transform // "?234567"
Upvotes: 0
Reputation: 236340
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"
}
Upvotes: 24
Reputation: 302
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: "**********")
Upvotes: 0
Reputation: 11555
You can try this:
var s = "123456"
let s2 = s.replacingCharacters(in: ...s.startIndex, with: "a")
s2 // "a23456"
Upvotes: 19
Reputation: 39374
In Swift 4.0
let inputString = "!Hello"
let outputString = String(inputString.dropFirst())
Answer
outputString = "Hello"
Upvotes: 2
Reputation: 247
In Swift 2.0 you can do something like this:-
let inputString = "!Hello"
let outputString = String(inputString.characters.dropFirst())
//Answer
outputString = "Hello"
Upvotes: 0
Reputation: 80265
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
Upvotes: 4
Reputation: 12109
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))
Upvotes: 0