在Swift中如何将字符串替换为字符串?
在Swift中如何将字符串替换为字符串?
在Swift中,我们可以使用`stringByReplacingOccurrencesOfString`来替换字符串中的内容。具体的代码如下:
let string = "Big red car"
let replaced = (string as NSString).stringByReplacingOccurrencesOfString("Big", withString: "Small")
然而,在Swift 5中,上述代码会在REPL中报错:`error: cannot invoke 'stringByReplacingOccurrencesOfString' with an argument list of type '(StringLiteralConvertible, withString: StringLiteralConvertible)'`。但是如果不用类型转换的话,代码是可以正常工作的。
有人问到使用的Xcode版本是多少,因为在Xcode 6.1.1中,这段代码可以编译并正常工作。当然,在REPL中使用NSString需要导入Foundation库。
对于Swift 3,我们需要这样写代码:`let replaced = string.replacingOccurrences(of: "Big", with: "Small")`。
需要注意的是,在Swift 3中,我们需要在`with`之前添加逗号,并在`with`之后添加冒号,具体代码如下:
let replaced = string.replacingOccurrences(of: "Big", with: "Small")
以上就是如何在Swift中替换字符串的方法。
在Swift中如何将一个字符串替换为另一个字符串?
在Swift中,我们可以使用`stringByReplacingOccurrencesOfString`方法来实现字符串的替换。下面是一个例子:
let s1 : String = "Red small car"
let s2 = s1.stringByReplacingOccurrencesOfString("small", withString: "big")
上述代码中,我们将字符串`s1`中的"small"替换为"big",并将结果赋值给`s2`。这样,`s2`的值将变为"Red big car"。
在Swift 4中,上述方法已经被替换为`replacingOccurrences(of:,with:)`。使用方法如下:
let s1 : String = "Red small car"
let s2 = s1.replacingOccurrences(of: "small", with: "big")
上述代码与之前的例子功能相同,将字符串`s1`中的"small"替换为"big",并将结果赋值给`s2`。
通过以上方法,我们可以轻松地在Swift中进行字符串的替换操作。