I'm trying to find what is the most effective way to get the longest string in a string array. For example :
let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]
and the outcome will be - "Game Of Thrones is just good"
I've tried using the maxElement
func, tho it's give the max string in a alphabetic ideas(maxElement()
).
Any suggestions? Thanks!
Swift strings can be treated as an array of individual characters. So, to return the length of a string you can use yourString. count to count the number of items in the characters array.
To find the maximum length of a string in a given list, you can use the max(lst, key=len) function to obtain the string with the maximum length and then pass this max string into the len() function to obtain the number of characters of the max string.
The longest string in the array of strings a is of length 7 . When you initialize the max with 0 or 1 , the expression max<strlen(a[i]) evaluate to true for any string whose length is greater than the value of max . Hence you will get the expected output.
Instead of sorting which is O(n log(n)) for a good sort, use max(by:)
which is O(n) on Array providing it a closure to compare string lengths:
Swift 4:
For Swift 4 you can get the string length with the count
property on String
:
let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]
if let max = array.max(by: {$1.count > $0.count}) {
print(max)
}
Swift 3:
Use .characters.count
on String
to get the string lengths:
let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]
if let max = array.max(by: {$1.characters.count > $0.characters.count}) {
print(max)
}
Swift 2:
Use maxElement
on Array providing it a closure to compare string lengths:
let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]
if let max = array.maxElement({$1.characters.count > $0.characters.count}) {
print(max)
}
Note: maxElement
is O(n). A good sort is O(n log(n)), so for large arrays, this will be much faster than sorting.
You can use reduce
to do this. It will iterate through your array, keeping track of the current longest string, and then return it when finished.
For example:
let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]
if let longestString = array.reduce(Optional<String>.None, combine:{$0?.characters.count > $1.characters.count ? $0:$1}) {
print(longestString) // "Game Of Thrones is just good"
}
(Note that Optional.None
is now Optional.none
in Swift 3)
This uses an nil
starting value to account for the fact that the array could be empty, as pointed out by @JHZ (it will return nil
in that case). If you know your array has at least one element, you can simplify it to:
let longestString = array.reduce("") {$0.characters.count > $1.characters.count ? $0:$1}
Because it only iterates through each element once, it will quicker than using sort()
. I did a quick benchmark and sort()
appears around 20x slower (although no point in premature optimisation, I feel it is worth mentioning).
Edit: I recommend you go with @vacawama's solution as it's even cleaner than reduce
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With