How to find the length of the shortest word in a string with VB.NET

1 Answer

0 votes
Imports System
Imports System.Linq

Module Program

    Function ShortestWordLength(text As String) As Integer
        ' Split on whitespace; RemoveEmptyEntries avoids empty strings
		Dim words() As String = text.Split({" "c, Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

        If words.Length = 0 Then
            Return 0
        End If

        ' LINQ-like approach using Enumerable.Min
        Dim minLen As Integer = words.Min(Function(w) w.Length)
        Return minLen
    End Function


    Sub Main()
        Dim input As String = "Find the shortest word length in this string"
        Dim result As Integer = ShortestWordLength(input)

        If result = 0 Then
            Console.WriteLine("No words found.")
        Else
            Console.WriteLine("Length of the shortest word: " & result)
        End If
    End Sub

End Module



' run:
'
'  Length of the shortest word: 2
'

 



answered Feb 11 by avibootz
...