我正在尝试用另一个字符替换字符串中的所有撇号 (') 字符。我正在运行此代码:
someString.replacingOccurrences(of: apost, with: "a")
我试图让post等于以下内容:
apost = "\'"
apost = #"'"#
apost = "'"
他们都没有从 someString 中删除撇号。
请让我知道是否有办法让 Swift 替换撇号。谢谢你。
我正在尝试用另一个字符替换字符串中的所有撇号 (') 字符。我正在运行此代码:
someString.replacingOccurrences(of: apost, with: "a")
我试图让post等于以下内容:
apost = "\'"
apost = #"'"#
apost = "'"
他们都没有从 someString 中删除撇号。
请让我知道是否有办法让 Swift 替换撇号。谢谢你。
该replacingOccurrences(...)
方法返回一个替换了撇号的新字符串对象。原始someString
对象不会因此而改变。你需要:
someString = someString.replacingOccurences(...)
如果发生了这种情况,请在 Xcode 中打开更多警告(或查看警告)。在我的设置中,这不会因为未使用的返回值而编译。
我遇到了同样的问题,它无法识别撇号或单引号。要查找和替换它们,请为每个字符使用 unicode。这对我有用。
let str = "mark's new name is 'mike'"
// apostrophe
var modstr = str.replacingOccurences(of: "\u{0027"}, with "")
// left single quote
modstr = modstr.replacingOccurences(of: "\u{2018"}, with "")
// right single quote
modstr = modstr.replacingOccurences(of: "\u{2019"}, with "")
// output
print(modstr)
输出:
marks new name is mike