let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]
结果将是 – “权力的游戏是好的”
我尝试过使用maxElement函数,因为它给出了字母思想中的最大字符串(maxElement()).
有什么建议?谢谢!
不要为了良好的排序而对O(n log(n))进行排序,而是使用max(by :),它是Array上的O(n),为它提供一个比较字符串长度的闭包:斯威夫特4:
对于Swift 4,您可以使用String上的count属性获取字符串长度:
let array = ["I'm Roi","Game Of Thrones is just good"]if let max = array.max(by: {.count >let array = ["I'm Roi","Game Of Thrones is just good"]if let max = array.max(by: {.characters.count >.count}) { print(max)}let array = ["I'm Roi","Game Of Thrones is just good"]if let max = array.maxElement({.characters.count > .characters.count}) { print(max)}.characters.count}) { print(max)}
斯威夫特3:
在String上使用.characters.count来获取字符串长度:
斯威夫特2:
在Array上使用maxElement,为它提供一个比较字符串长度的闭包:
注意:maxElement是O(n).一个好的排序是O(n log(n)),因此对于大型数组,这将比排序快得多.
总结以上是内存溢出为你收集整理的Swift – 在[String]数组中找到最长字符串的最佳实践全部内容,希望文章能够帮你解决Swift – 在[String]数组中找到最长字符串的最佳实践所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)