replacementOccurrences()中的错误?

问题描述 投票:0回答:2

我想知道String函数replacementOccurrences(of:String,with:String)是否有错误:

let s = "Hello     World!"
let cleaned : String = s.replacingOccurrences(of: "  ", with: " ")
print("cleaned = '\(cleaned)'")

我想将多个空格替换为一个

"  " to " "

但字符串保持不变。我已经在obj-c中完成了数百次,所以这是Swift中的一个错误吗?

swift
2个回答
3
投票

这不是一个错误。您将用一个空格替换每个出现的2个空格。该方法不能递归工作,因此5个空格减少到3。

您可以使用正则表达式,它用一个空格替换所有出现的一个或多个空格:

let s = "Hello     World!"
let cleaned = s.replacingOccurrences(of: " +", with: " ", options: .regularExpression)
print("cleaned = '\(cleaned)'")

1
投票

正如Vadian所提到的,这不是一个错误,这就是你的代码应该如何工作。

这是获得相同结果的另一种方法:

let cleaned = s.components(separatedBy: .whitespaces).filter({ !$0.isEmpty }).joined(separator: " ")

首先用空格分隔字符串,然后使用filter排除所有空格,然后连接用空格分隔它们的字符串的单词。

© www.soinside.com 2019 - 2024. All rights reserved.