stringByReplacingOccurrencesOfString不起作用?

时间:2014-06-04 15:56:35

标签: objective-c swift

我正在尝试翻译这个Objective-C代码:

if ([[self.appStoreCountry stringByReplacingOccurrencesOfString:@"[A-Za-z]{2}" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, 2)] length])

所以我试着写下这段代码:

if !self.appStoreCountry.stringByReplacingOccurrencesOfString("[A-Za-z]{2}", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: Range(start: 0, end: 2)).isEmpty

问题是stringByReplacingOccurrencesOfString部分似乎没有返回字符串。我收到了来自xcode的错误消息:Cannot convert the expression's type 'Bool' to type 'String'.

我调查了一下并尝试了:

let replaced = self.appStoreCountry.stringByReplacingOccurrencesOfString("[A-Za-z]{2}", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: Range(start: 0, end: 2))

错误消息类似但更奇怪:Cannot convert the expression's type 'String' to type 'String'.

我做错了什么或者我应该向Apple提交错误吗?

5 个答案:

答案 0 :(得分:7)

请记住,Foundation的类型与Swift的类型不同。 Swift中的String不是NSString,而Range不是NSRange。这确实有效:

let country = self.appStoreCountry // if self.appStoreCountry is an NSString
let country: NSString = self.appStoreCountry // if self.appStoreCountry is a Swift string

let replaced = country.stringByReplacingOccurrencesOfString("[A-Za-z]{2}", withString: "", options: .RegularExpressionSearch, range: NSMakeRange(0, 2))

另请注意.RegularExpressionSearch的简写符号,这使得在Swift中使用枚举更容易。

答案 1 :(得分:4)

extension String{
    func exclude(find:String) -> String {
        return stringByReplacingOccurrencesOfString(find, withString: "", options: .LiteralSearch, range: nil)
    }
    func replaceAll(find:String, with:String) -> String {
        return stringByReplacingOccurrencesOfString(find, withString: with, options: .LiteralSearch, range: nil)
    }
}
"1-2-3-4-5-6-7-8-9-0".exclude("-")                 // "1234567890" 
"1-2-3-4-5-6-7-8-9-0".replaceAll("-", with: "+")   // "1+2+3+4+5+6+7+8+9+0"

答案 2 :(得分:1)

尝试此代码:

var originalString="Hello World"

    var needToReplaceString = "Hello"
    var replaceString = " Hi"


    var newString = originalString.stringByReplacingOccurrencesOfString(needToReplaceString, withString: replaceString, options: nil, range: nil)

    println(newString)

答案 3 :(得分:0)

打开游乐场并添加此代码,现在它是正确的:

var str = NSString(CString: "en")

str = str.stringByReplacingOccurrencesOfString("[A-Za-z]{2}", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: NSRange(location: 0, length: 2))

if str == ""
{
    var a = "true"
} else {
    var b = "false"
}

你的问题是:

  • .isEmpty不是NSString的方法
  • 你正在使用Range()而不是NSString的方法.stringByReplacingOccurrencesOfString所要求的NSRange
  • 因为你的replace返回一个空字符串而不是一个nil对象,你必须在if语句中测试“”

答案 4 :(得分:0)

let maskCharSet = NSCharacterSet(charactersInString: " ()-.")
let cleanedString = phoneNumber.componentsSeparatedByCharactersInSet(maskCharSet).reduce("", combine: +)