Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell | Array get the longest string

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!

like image 857
XXInvidiaXX Avatar asked May 13 '14 08:05

XXInvidiaXX


People also ask

How do you find the maximum length of a string in an array?

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.

How do you find the longest word in an array?

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.


1 Answers

@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
like image 154
Frode F. Avatar answered Oct 26 '22 23:10

Frode F.