![](/img/trans.png)
[英]How do I find a character followed by a character in a char array Java?
[英]How do I find the character count of each item in an array
我正在写一个函数,该函数从字符数超过8的字典中打印字符串值。这是到目前为止的内容,但是我不确定如何公式化where条件,以便它查看字符数在数组中的每个字符串值中。
var stateCodes = ["NJ": "New Jersey", "CO": "Colorado", "WI": "Wisconsin", "OH": "Ohio"]
func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {
let fullStateNames = Array(stateCodes.values)
for _ in fullStateNames where fullStateNames.count > 8 {
print(fullStateNames)
return fullStateNames
}
return fullStateNames
}
printLongState(stateCodes)
如果要使用for循环,则可以像这样进行操作。
func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {
var fullStateNames = [String]()
for (_, value) in dictionary where value.characters.count > 8 {
fullStateNames.append(value)
}
return fullStateNames
}
但这不是Swift中的Swifty方法,您可以做的是可以在您的Dictionary
使用flatMap
来创建string
数组或使用dictionary.values.filter
在字典中使用flatMap
func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {
return dictionary.flatMap { $1.characters.count > 8 ? $1 : nil }
}
// Call it like this way.
var stateCodes = ["NJ": "New Jersey", "CO": "Colorado", "WI": "Wisconsin", "OH": "Ohio"]
print(printLongState(stateCodes)) //["Wisconsin", "New Jersey"]
在dictionary.values
上使用过滤器
func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {
return dictionary.values.filter { $0.characters.count > 8 }
}
只是filter
您的结果,而不是使用for-loop
:
如果要返回字典,请使用以下命令:
func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {
let overEightChars = stateCodes.filter({ $0.value.characters.count > 8 })
return overEightChars
}
如果要返回字符串数组,请使用以下命令:
func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {
return dictionary.values.filter { $0.characters.count > 8 }
}
尝试将filter
与characters.count
一起使用,如下所示:
var states = ["NJ": "New Jersey", "CO": "Colorado", "WI": "Wisconsin", "OH": "Ohio"]
states.filter({ (_, value) -> Bool in
return value.characters.count > 8
}).map({ (_, value) in
print(value)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.