我正在寻找一种方法来取代字符在一个Swift字符串。
示例:“This is my string”
我想用“+”替换“”以获得“This+is+my+string”。
我怎样才能做到这一点呢?
我正在寻找一种方法来取代字符在一个Swift字符串。
示例:“This is my string”
我想用“+”替换“”以获得“This+is+my+string”。
我怎样才能做到这一点呢?
当前回答
我认为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"
其他回答
迅速扩展:
extension String {
func stringByReplacing(replaceStrings set: [String], with: String) -> String {
var stringObject = self
for string in set {
stringObject = self.stringByReplacingOccurrencesOfString(string, withString: with)
}
return stringObject
}
}
继续使用let replacedString = yorString。stringbyreplacement (replaceStrings: [" ","?","."],加上:“+”)
函数的速度是我几乎不能感到骄傲的,但是你可以在一次传递一个String数组来进行多次替换。
从Swift 2开始,String不再符合SequenceType。换句话说,你不能用for…在循环。
简单而简单的方法是将String转换为Array以获得索引的好处:
let input = Array(str)
我记得当我试图索引到字符串不使用任何转换。我真的很沮丧,因为我不能想出或达到一个理想的结果,我准备放弃了。 但我最终创建了我自己的解决方案,这里是扩展的完整代码:
extension String {
subscript (_ index: Int) -> String {
get {
String(self[self.index(startIndex, offsetBy: index)])
}
set {
remove(at: self.index(self.startIndex, offsetBy: index))
insert(Character(newValue), at: self.index(self.startIndex, offsetBy: index))
}
}
}
现在,你可以像你最初想要的那样,使用索引从字符串中读取和替换单个字符:
var str = "cat"
for i in 0..<str.count {
if str[i] == "c" {
str[i] = "h"
}
}
print(str)
这是一种简单而有用的方式来使用它,并通过Swift的字符串访问模型。 现在,下次你会觉得它很顺利,因为你可以循环字符串,而不是将它强制转换到数组中。
尝试一下,看看它是否有帮助!
你可以用这个:
let s = "This is my string"
let modified = s.replace(" ", withString:"+")
如果你在你的代码中添加这个扩展方法:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
}
斯威夫特3:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
}
Xcode 11•Swift 5.1
StringProtocol replacingOccurrences的突变方法可以实现如下:
extension RangeReplaceableCollection where Self: StringProtocol {
mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<String.Index>? = nil) {
self = .init(replacingOccurrences(of: target, with: replacement, options: options, range: searchRange))
}
}
var name = "This is my string"
name.replaceOccurrences(of: " ", with: "+")
print(name) // "This+is+my+string\n"
修改现有可变字符串的类别:
extension String
{
mutating func replace(originalString:String, withString newString:String)
{
let replacedString = self.stringByReplacingOccurrencesOfString(originalString, withString: newString, options: nil, range: nil)
self = replacedString
}
}
使用:
name.replace(" ", withString: "+")