旧行李 2014-06-13 08:28 采纳率: 25%
浏览 508
已采纳

有什么方法可以替换 Swift String 中的字符吗?

I'm looking for a way to replace characters in a Swift String.

Example: "This is my string"

I'd like to replace with + to get: "This+is+my+string".

How can I achieve this?

转载于:https://stackoverflow.com/questions/24200888/any-way-to-replace-characters-on-swift-string

  • 写回答

15条回答 默认 最新

  • 游.程 2014-06-13 08:45
    关注

    This answer has been updated for Swift 4. If you're still using Swift 1, 2 or 3 see the revision history.

    You have a couple of options. You can do as @jaumard suggested and use replacingOccurrences()

    let aString = "This is my string"
    let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
    

    And as noted by @cprcrack below, the options and range parameters are optional, so if you don't want to specify string comparison options or a range to do the replacement within, you only need the following.

    let aString = "This is my string"
    let newString = aString.replacingOccurrences(of: " ", with: "+")
    

    Or, if the data is in a specific format like this, where you're just replacing separation characters, you can use components() to break the string into and array, and then you can use the join() function to put them back to together with a specified separator.

    let toArray = aString.components(separatedBy: " ")
    let backToString = toArray.joined(separator: "+")
    

    Or if you're looking for a more Swifty solution that doesn't utilize API from NSString, you could use this.

    let aString = "Some search text"
    
    let replaced = String(aString.map {
        $0 == " " ? "+" : $0
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)

报告相同问题?

悬赏问题

  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。