面试题答案
一键面试let originalString = "Hello, World!"
let newString = originalString.replacingOccurrences(of: "l", with: "x")
print(newString)
原理:在Swift中,String
类型提供了replacingOccurrences(of:with:)
方法。这个方法用于在字符串中查找指定的子字符串(这里是"l"
),并将其替换为另一个指定的子字符串(这里是"x"
)。该方法返回一个新的字符串,而不会修改原始字符串,因为Swift中的字符串是值类型,具有不可变性。