I have an array of strings of variable length. Currently I have a loop that iterates through the array to find the longest string in array. Is there any way I could use LINQ to write it in more efficient and / or cleaner way?
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.
In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length.
Python Max Length of String in List. 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.
It won't be much more efficient, however it would be a bit cleaner to do something like:
var strings = new string[] { "1", "02", "003", "0004", "00005" }; string longest = strings.OrderByDescending( s => s.Length ).First();
Output: 00005
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