I would like to get the longest string in an array, without looping through the whole array with foreach or do...until.
I tried this:
$Namelength = ($array | Measure-Object -Maximum).Maximum.ToString().Length
It seems to work with numbers. But not with strings (my strings contain "," "." "-" and "_")
I am somehow just getting some long strings, but not the longest - It is more like an average value.
Any idea to solve that?
Greetings and thanks in advance!
Approach: Follow the steps below to solve the problem: Traverse the given array of strings. Calculate the maximum length among all the strings from the array and store it in a variable, say len. Now, traverse the array of string again and print those strings from the array having a length equal to len.
Find the Longest Word With the sort() Method For this solution, we will use the Array. prototype. sort() method to sort the array by some ordering criterion and then return the length of the first element of this array. The sort() method sorts the elements of an array in place and returns the array.
@Kayasax's answer will give you the string(value) for the longest string. The reason your code didn't work was because you measured the items in the array, not the length. For that, you need to specify the -Property Length
parameter in Measure-Object
, like this:
PS> ("lalala","hehe","hi" | Measure-Object -Maximum -Property Length).Maximum
6
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