2017-06-19 53 views
0

我必须在字符串中找到3个字符中的1个。我怎样才能做到这一点?查找字符串中的3个字符中的1个

我尝试这样做:

let value = "from 3,95 €" 
let wanted: Character = "£", "€" OR "₹" 
if let idx = value.characters.index(of: wanted) {          
    print("Found \(wanted)") 
} else { 
    print("Not found") 
} 

谢谢!

+0

你只是想检查字符串是否有该字符,或者你想要该字符的索引吗? –

+0

为什么你不使用'NSNumberFormatter'的任何理由?选中这个[documentation](https://developer.apple.com/documentation/foundation/numberformatter)。 – LinusGeffarth

+0

@Nirav D:是的,我只想检查一个字符串中是否有这些字符。不,我不需要索引.... – Saintz

回答

1

并不确切地知道你想要达到的目标,但如果你想知道哪些字符串从这3个字符包含,那么你可以做出这样的事情。

let value = "from 3,95 €" 
let wanted: [Character] = ["£", "€", "₹"] 
if let result = value.characters.first(where: { wanted.contains($0) }) { 
    print("Found \(result)") 
} else { 
    print("Not found") 
} 

输出

Found € 

编辑:如果你只是要检查字符串中包含然后用contains(where:)代替first(where:)

if value.characters.contains(where: { wanted.contains($0) }) { 
    print("Found") 
} else { 
    print("Not found") 
} 
+0

我只想检查一个字符串中是否有这些字符。不,我不需要索引.... – Saintz

+0

@Saintz检查编辑的答案 –

+0

包含(其中:)不会帮助:他们说:修复它:删除“其中:” – Saintz

0

,如果你只想确定它们是否存在试试这个:

let value = "from 3,95 €" 
let wanted = CharacterSet(charactersIn: "£€₹") 
if value.rangeOfCharacter(from: wanted) != nil { 
    print("Found") 
} else { 
    print("Not found") 
} 
1

斯威夫特3:

if let dataArray = value.characters.filter{ $0 == "£" || $0 == "€" || $0 == "₹" }, dataArray.count > 0 { 
//you have at least one of them in your string, so do whatever you want here 
} 
+0

对不起,还有一个问题。如果我想在字符串中找不到这些字符中的任何一个,它是? : !value.characters.filter {$ 0 ==“£”|| $ 0 ==“€”|| $ 0 ==“₹”},dataArray.count> 0 {... – Saintz

+0

您可以使用''''else {}'''语句。 '''if let dataArray = ...> 0 {}其他{//没有找到它们}''' – Mina

相关问题