我试图添加一个从文本输入中获取的字符串的第一个字符,然后将其替换为另一个字符,但是新字符串将替换每个具有0
的值,而不仅仅是初始数字。下面是我尝试过的代码
let swiftyString = phoneNumberField.text?.replacingOccurrences(of: "0", with: "44")
print("STRING \(swiftyString!)")
答案 0 :(得分:3)
您可以尝试
let res = "44\(swiftyString.dropFirst())"
或创建
extension String {
mutating func replaceFirst(_ str:String) {
self = str + self.dropFirst()
}
}
答案 1 :(得分:3)
如果要替换第一个字符:
guard let input = phoneNumberField.text as? String{
return
}
let outPut = "44" + String(input.dropFirst())
答案 2 :(得分:2)
使用insert(_,at:)
代替replacingOccurrences
if var phone = phoneNumberField.text?.dropFirst() {
phone.insert("44", at: phone.startIndex)
}
要替换第N个字符:
extension String {
func replace(_ with: String, at index: Int) -> String {
var modifiedString = String()
for (i, char) in self.enumerated() {
modifiedString += String((i == index) ? with : String(char))
}
return modifiedString
}
}
使用:
let string = "wqrtyry"
let dd = string.replace("R", at: 2)
print(dd)
答案 3 :(得分:2)
只需使用regularExpression
选项,前导插入符(^
)仅考虑字符串的开头
let swiftyString = phoneNumberField.text?.replacingOccurrences(of: "^0", with: "44", options: .regularExpression)
或在扩展程序中使用replaceSubrange
extension String {
mutating func replaceLeadingZero(with string: String) {
if hasPrefix("0") { replaceSubrange(...startIndex, with: string) }
}
}
let swiftyString = phoneNumberField.text?.replaceLeadingZero(with: "44")
答案 4 :(得分:1)
如果您喜欢冒险,可以使用下面的代码
var string = "05942208638"
var ranges: [Range<String.Index>] = []
var start = string.startIndex
while start < string.endIndex,
let range = string.range(of: "0", range: start..<string.endIndex) {
ranges.append(range)
start = range.upperBound
if ranges.count == 1 { break }
}
for range in ranges.reversed() {
string.replaceSubrange(range, with: "44")
}
print(string) //prints 445942208638
答案 5 :(得分:1)
让swiftyString =“ 44” + phoneNumberField.text?.dropFirst()