0

我正在尝试用另一个字符替换字符串中的所有撇号 (') 字符。我正在运行此代码:

someString.replacingOccurrences(of: apost, with: "a")

我试图让post等于以下内容:

apost = "\'"
apost = #"'"#
apost = "'"

他们都没有从 someString 中删除撇号。

请让我知道是否有办法让 Swift 替换撇号。谢谢你。

4

3 回答 3

2

replacingOccurrences(...)方法返回一个替换了撇号的新字符串对象。原始someString对象不会因此而改变。你需要:

someString = someString.replacingOccurences(...)

如果发生了这种情况,请在 Xcode 中打开更多警告(或查看警告)。在我的设置中,这不会因为未使用的返回值而编译。

于 2020-03-28T11:09:05.763 回答
1

我遇到了同样的问题,它无法识别撇号或单引号。要查找和替换它们,请为每个字符使用 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
于 2021-07-18T17:59:39.557 回答
1
于 2021-09-15T22:19:35.020 回答