快速替换字符串中的第一个字符 [英] Swift replace first character in string
问题描述
一个非常简单的问题,我如何替换字符串的第一个字符.我可能在做完全错误的事情,但我根本无法使它正常工作.
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.
我已经尝试过:var query = url.query!.stringByReplacingOccurrencesOfString("&", withString: "?", options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, 1))
但是它给了我以下错误:
But it gives me the following error:
不能使用类型为'(String,withString:String,options:NSStringCompareOptions,range:NSRange)'的参数列表调用'stringByReplacingOccurrencesOfString'
Cannot invoke 'stringByReplacingOccurrencesOfString' with an argument list of type '(String, withString: String, options: NSStringCompareOptions, range: NSRange)'
当我删除NSMakeRange并将其更改为nil时,它可以工作,但是它将替换字符串中的所有&'.
When I remove the NSMakeRange and change it to nil, it works, but it replaces all the &'s in the string.
推荐答案
您可以尝试以下操作:
var s = "123456"
let s2 = s.replacingCharacters(in: ...s.startIndex, with: "a")
s2 // "a23456"
这篇关于快速替换字符串中的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!