Cenk YAGMUR
Cenk YAGMUR

Reputation: 3451

Dart list get the longest string

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

Answers (4)

Toglefritz
Toglefritz

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

Sparko Sol
Sparko Sol

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

Minato
Minato

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

Ashkan Sarlak
Ashkan Sarlak

Reputation: 7344

final longestString = list.fold<String>('', 
  (previousValue, element) => 
    element.length > previousValue.length ? element : previousValue)

Upvotes: -1

Related Questions