我正在寻找一种方法来取代字符在一个Swift字符串。
示例:“This is my string”
我想用“+”替换“”以获得“This+is+my+string”。
我怎样才能做到这一点呢?
我正在寻找一种方法来取代字符在一个Swift字符串。
示例:“This is my string”
我想用“+”替换“”以获得“This+is+my+string”。
我怎样才能做到这一点呢?
当前回答
下面是Swift 3的示例:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
其他回答
很少发生在我身上,我只是想改变字符串中的(一个单词或字符)
所以我用了字典
extension String{
func replace(_ dictionary: [String: String]) -> String{
var result = String()
var i = -1
for (of , with): (String, String)in dictionary{
i += 1
if i<1{
result = self.replacingOccurrences(of: of, with: with)
}else{
result = result.replacingOccurrences(of: of, with: with)
}
}
return result
}
}
使用
let mobile = "+1 (800) 444-9999"
let dictionary = ["+": "00", " ": "", "(": "", ")": "", "-": ""]
let mobileResult = mobile.replace(dictionary)
print(mobileResult) // 001800444999
你可以测试这个:
let newString = test。stringByReplacingOccurrencesOfString(" ", withString: "+",选项:nil,范围:nil)
斯威夫特4:
let abc = "Hello world"
let result = abc.replacingOccurrences(of: " ", with: "_",
options: NSString.CompareOptions.literal, range:nil)
print(result :\(result))
输出:
result : Hello_world
下面是Swift 3的示例:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
我认为Regex是最灵活和可靠的方法:
var str = "This is my string"
let regex = try! NSRegularExpression(pattern: " ", options: [])
let output = regex.stringByReplacingMatchesInString(
str,
options: [],
range: NSRange(location: 0, length: str.characters.count),
withTemplate: "+"
)
// output: "This+is+my+string"