2017-05-26 57 views
0

我有一个问题。我为移动应用程序编写测试。在此刻,我比较不同货币的价格,如英镑,欧元,印度等。可能的比较应该是“现在£1.678,95”。对我来说,削减“现在”,切割空白 - 简而言之,就是让字符串处于一个可能的Int或Double形式,这对我来说没有任何问题。但现在我在法国。在法国,编队是“维持2 500,00€”。 “维护者”没有问题,价格以外的空白没有问题,“€”没有问题。如何从字符串中删除一些空格?

但是价格在2到500之间。如果我运行我的测试,我只剩下“2”,剩下的就不见了! 我该怎么做,这个空白不应该在这里切割。它应该从“2 500,00”缩减为“2500,00”。

希望你有个想法:)谢谢!

我在这一刻代码:

var firstPrice = XCUIApplication().collectionViews.cells.element(boundBy: 0).staticTexts.element(boundBy: 2).label 

firstPrice = firstPrice.replacingOccurrences(of: "£", with: "") 
firstPrice = firstPrice.replacingOccurrences(of: "€", with: "") 
firstPrice = firstPrice.replacingOccurrences(of: "₹", with: "") 

let firstPriceArray = firstPrice.components(separatedBy: .whitespaces).filter { !$0.isEmpty } 
firstPrice = firstPriceArray[1] 

let firstPriceTrimmedDouble = firstPrice.toDouble(with: SiteIDHelper.locale(from: SiteIDHelper.SiteID(rawValue: Int(sideIDS))!))! 

print(firstPriceTrimmedDouble) 
+1

你或许应该使用[号码格式化程序](https://stackoverflow.com/questions/544314/easiest-way-to-convert-a-nsstring-to-its-currency-equivalent-in-cocoa)而不是这样做。 – Moritz

+0

只需用'.regularExpression'选项替换'[^ 0-9。,]'的任何出现。 – Sulthan

回答

1

艰难,因为你不知道字符串的区域设置。 1234欧元可以写成英文风格的€ 1,234.00,或法文和德文风格的1.234,00 €。 (欧元在英格兰也很常见)。

从你提供的,你可以删除的第一个词,然后删除所有空格,逗号,顿号和货币符号从剩余的将其转换为双前有限的例子:

let priceString = "maintenant 2 500,00 €" 
let unwanted = " ,.£€₹" 
var doubleValue : Double? 

if let range = priceString.range(of: " ") { 
    let chars = priceString[range.upperBound..<priceString.endIndex] 
     .characters.filter({ !unwanted.characters.contains($0) }) 
    doubleValue = Double(String(chars)) 
} 

// run your asserts here 
+0

非常感谢,它的作品!但是,你能告诉我,我如何从“if”循环中得到结果来处理它? – Saintz

+0

我没有得到'if'以外的结果。我的代码如下所示: let unwanted =“,。£€₹” var firstPriceTrimmedDouble:Double? if let range = firstPrice.range(of:“”){ let chars = firstPrice [range.upperBound .. Saintz

+0

它打印正确的价格,例如。 G。价格是“ab 269,00”,它打印“26900.0”,但'if'循环结束后,firstPriceTrimmedDouble再次为'nil'。 – Saintz

0

真不明白你是什么后...但除去所有空格,试试这个:

var price: String = ... 
while let range = price.rangeOfCharacter(from: .whitespaces) { 
    price.removeSubrange(range) 
}