我正在寻找一种方法来取代字符在一个Swift字符串。

示例:“This is my string”

我想用“+”替换“”以获得“This+is+my+string”。

我怎样才能做到这一点呢?


当前回答

你可以用这个:

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)
    }
}

其他回答

迅速扩展:

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 4.2中很容易做到。只需使用replacingOccurrences(of: " ", with: "_")进行替换

var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)

从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的字符串访问模型。 现在,下次你会觉得它很顺利,因为你可以循环字符串,而不是将它强制转换到数组中。

尝试一下,看看它是否有帮助!

var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)

我实现了这个非常简单的func:

func convap (text : String) -> String {
    return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}

所以你可以这样写:

let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')