Reputation: 3451
I want to get first longest string ? How can i do this ?
List<String> list = ['hi', 'hello', 'frozen', 'big mistake', 'cool daddy'];
Upvotes: 1
Views: 1394
Reputation: 155
The solution posted by Sparko Sol could also be used in an extension on List<String>
to make it easier to reuse this method anywhere in the codebase. Such an extension could look something like
extension Longest on List<String> {
/// Returns the longest element in a [List<String>]
String longest() {
return reduce((a, b) {
return a.length > b.length ? a : b;
});
}
}
Then, to use this extension, you could simply write something like
String longestString = list.longest();
Upvotes: 0
Reputation: 717
this is the shortest solution, which will return the longest string:
list.reduce((a, b) {
return a.length > b.length ? a : b;
})
another alternative is:
list.sort((a, b) {
return b.length - a.length;
});
print(list[0]);
Upvotes: 6
Reputation: 412
Check the below function i have done in my project to get the longest string.
long_string(arr) {
var longest = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i].length > longest.length) {
longest = arr[i];
}
}
return longest;
}
And you can call the function like below to get the longest string
var arr = ["Orebro", "Sundsvall", "Hudriksvall", "Goteborgsdsdsds"];
print(long_string(arr));
Upvotes: 1
Reputation: 7344
final longestString = list.fold<String>('',
(previousValue, element) =>
element.length > previousValue.length ? element : previousValue)
Upvotes: -1