Is there a short way to find the longest string in a string array?
Something like arr.Max(x => x.Length);
?
I wrote this code: char a[100][100] = {"solol","a","1234567","123","1234"}; int max = -1; for(int i=0;i<5;i++) if(max<strlen(a[i])) max=strlen(a[i]); cout<<max; The output it gives is -1. But when I initialize the value of max by 0 instead of 1, the code works fine.
Use Python's built-in max() function with a key argument to find the longest string in a list. Call max(lst, key=len) to return the longest string in lst using the built-in len() function to associate the weight of each string—the longest string will be the maximum.
Available since Javascript 1.8/ECMAScript 5 and available in most older browsers:
var longest = arr.reduce( function (a, b) { return a.length > b.length ? a : b; } );
Otherwise, a safe alternative:
var longest = arr.sort( function (a, b) { return b.length - a.length; } )[0];
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