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

示例:“This is my string”

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

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


当前回答

这在swift 4.2中很容易做到。只需使用replacingOccurrences(of: " ", with: "_")进行替换

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

其他回答

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: "+")

下面是Swift 3的示例:

var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
   stringToReplace?.replaceSubrange(range, with: "your")
} 

如果你不想使用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"。

很少发生在我身上,我只是想改变字符串中的(一个单词或字符)

所以我用了字典

  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

这在swift 4.2中很容易做到。只需使用replacingOccurrences(of: " ", with: "_")进行替换

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