我正在寻找一种替换Swift String
中的字符的方法。
示例:"This is my string"
我想将替换为
+
以获取:"This+is+my+string"
。
我怎样才能做到这一点?
答案 0 :(得分:808)
此答案已针对Swift 4进行了更新。如果您仍在使用Swift 1,2或3,请查看修订历史记录。
你有几个选择。您可以按@jaumard建议并使用replacingOccurrences()
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
如下面的@cprcrack所述,options
和range
参数是可选的,因此如果您不想指定字符串比较选项或范围来进行替换,则只需需要以下内容。
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")
或者,如果数据采用这样的特定格式,您只需要替换分隔字符,则可以使用components()
将字符串分解为数组,然后可以使用{{1函数将它们与指定的分隔符一起放回。
join()
或者,如果您正在寻找更多不使用NSString API的Swifty解决方案,您可以使用它。
let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")
答案 1 :(得分:60)
您可以使用:
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)
}
}
答案 2 :(得分:44)
Swift 3,Swift 4,Swift 5解决方案
let exampleString = "Example string"
//Solution suggested above in Swift 3.0
let stringToArray = exampleString.components(separatedBy: " ")
let stringFromArray = stringToArray.joined(separator: "+")
//Swiftiest solution
let swiftyString = exampleString.replacingOccurrences(of: " ", with: "+")
答案 3 :(得分:18)
你测试过这个:
var test = "This is my string"
let replaced = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
答案 4 :(得分:13)
let abc = "Hello world"
let result = abc.replacingOccurrences(of: " ", with: "_",
options: NSString.CompareOptions.literal, range:nil)
print(result :\(result))
输出:
result : Hello_world
答案 5 :(得分:8)
符合Sunkas的Swift 3解决方案:
extension String {
mutating func replace(_ originalString:String, with newString:String) {
self = self.replacingOccurrences(of: originalString, with: newString)
}
}
使用:
var string = "foo!"
string.replace("!", with: "?")
print(string)
输出:
foo?
答案 6 :(得分:7)
我正在使用此扩展程序:
extension String {
func replaceCharacters(characters: String, toSeparator: String) -> String {
let characterSet = NSCharacterSet(charactersInString: characters)
let components = self.componentsSeparatedByCharactersInSet(characterSet)
let result = components.joinWithSeparator("")
return result
}
func wipeCharacters(characters: String) -> String {
return self.replaceCharacters(characters, toSeparator: "")
}
}
用法:
let token = "<34353 43434>"
token.replaceCharacters("< >", toString:"+")
答案 7 :(得分:6)
修改现有可变字符串的类别:
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: "+")
答案 8 :(得分:4)
基于Ramis' answer的Swift 3解决方案:
extension String {
func withReplacedCharacters(_ characters: String, by separator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
return components(separatedBy: characterSet).joined(separator: separator)
}
}
尝试根据Swift 3命名约定提出适当的函数名称。
答案 9 :(得分:2)
var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)
答案 10 :(得分:1)
以下是Swift 3的示例:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
答案 11 :(得分:1)
这在Swift 4.2中很容易。只需使用replacingOccurrences(of: " ", with: "_")
进行替换
var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)
答案 12 :(得分:1)
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"
答案 13 :(得分:0)
我已经实现了这个非常简单的功能:
func convap (text : String) -> String {
return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}
所以你可以写:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')
答案 14 :(得分:0)
我认为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"
答案 15 :(得分:0)
快速扩展:
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.stringByReplacing(replaceStrings: [" ","?","."], with: "+")
这个功能的速度是我很难引以为傲的,但你可以在一遍中传递一个String
数组来进行多次替换。
答案 16 :(得分:0)
如果您不想使用Objective-C NSString
方法,则可以使用split
和join
:
var string = "This is my string"
string = join("+", split(string, isSeparator: { $0 == " " }))
split(string, isSeparator: { $0 == " " })
返回一个字符串数组(["This", "is", "my", "string"]
)。
join
使用+
加入这些元素,从而产生所需的输出:"This+is+my+string"
。
答案 17 :(得分:0)
很少发生在我身上,我只想更改String
中的(单词或字符)
所以我用了Dictionary
extension String{
func replaceDictionary(_ 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.replaceDictionary(dictionary)
print(mobileResult) // 001800444999
答案 18 :(得分:0)
您可以对此进行测试:
let newString = test.stringByReplacingOccurrencesOfString(“”,withString:“ +”,选项:无,范围:无)
答案 19 :(得分:0)
const serviceClient = new ShareServiceClient(
`https://${storageAccountName}.file.core.windows.net`,
credential
);
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryPath);
const dirIter = directoryClient.listFilesAndDirectories();
const list = [];
for await (const item of dirIter) {
list.push({name: item.name, metadata????}); // Need item metadata
}
输出为
var str = "This is my string"
print(str.replacingOccurrences(of: " ", with: "+"))
答案 20 :(得分:0)
从 Swift 2 开始,String
不再符合 SequenceType
。换句话说,您不能使用 for...in
循环遍历字符串。
简单易行的方法是将 String
转换为 Array
以获得索引的好处,就像这样:
let input = Array(str)
我记得当我试图在不使用任何转换的情况下索引到 String
时。我真的很沮丧,我无法想出或达到想要的结果,并准备放弃。
但我最终创建了自己的解决方案,这是扩展的完整代码:
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 的 String 访问模型是一种简单而有用的方法。
现在,当您可以按原样循环遍历字符串而不是将其转换为 Array
时,下次您会感觉一切顺利。
试试看,看看是否有帮助!
答案 21 :(得分:-1)
以下是var r = {"meta":{"code":200,"requestId":"595cc7784c1f67701d721227"},"response":{"venues":[{"id":"5564370c498e52484ec3249f","name":"Aras Döner & Kokoreç","contact":{},"location":{"lat":41.187417726573926,"lng":27.76829713785891,"labeledLatLngs":[{"label":"display","lat":41.187417726573926,"lng":27.76829713785891}],"distance":12,"cc":"TR","country":"Türkiye","formattedAddress":["Türkiye"]},"categories":[{"id":"4bf58dd8d48988d16e941735","name":"Fast Food Restoranı","pluralName":"Fast Food Restoranları","shortName":"Fast Food","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/fastfood_","suffix":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":2038,"usersCount":740,"tipCount":0},"allowMenuUrlEdit":true,"beenHere":{"lastCheckinExpiredAt":0},"specials":{"count":0,"items":[]},"hereNow":{"count":0,"summary":"Burada kimse yok","groups":[]},"referralId":"v-1499252600","venueChains":[],"hasPerk":false}],"confident":false}};
var venues = r.response.venues;
for (i = 0; i < venues.length; i++) {
console.log(venues[i].name)
}
上的就地出现替换方法的扩展,它不会产生不必要的副本,并且可以执行所有操作:
String
(方法签名也模仿内置extension String {
mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
var range: Range<Index>?
repeat {
range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..<self.endIndex }, locale: locale)
if let range = range {
self.replaceSubrange(range, with: replacement)
}
} while range != nil
}
}
方法的签名)
可以按以下方式使用:
String.replacingOccurrences()