Dim longestWord = String.Empty
For Each word in strArray
If Not String.IsNullOrEmpty(word) AndAlso word.Length > longestWord.Length Then
longestWord = word
End If
Next
** updated to account for null string **
Frage
I have an array in Visual Basic that needs to have the longest word returned. How do I go about locating the longest word in a String array? Any help is greatly appreciated!
Lösung 2
Dim longestWord = String.Empty
For Each word in strArray
If Not String.IsNullOrEmpty(word) AndAlso word.Length > longestWord.Length Then
longestWord = word
End If
Next
** updated to account for null string **
Andere Tipps
A LINQ alternative is this:
Dim strings = New String() {"1", "02", "003", "0004", "00005"}
Dim longest As String = strings.OrderByDescending(Function(s) s.Length).FirstOrDefault()
Something like this... (It's c#, but should port to VB easily)
string[] stringArray = new string[] { "One", "Two", "Three", "Four" };
string longest = stringArray.OrderByDescending(x => x.Length).FirstOrDefault();
If I were to do this with Linq in C#, I would do it something like this:
var strings = new string[3] { "abc", "defg", "hijkl" };
string longest = strings.OrderByDescending(s => s.Length).FirstOrDefault();