How to find the largest and the smallest word in a string with VB.NET

2 Answers

0 votes
Module Module1

    Sub Main()

        Dim s As String = "vb sharp c cpp python java"

        Dim words() = s.Split(" ")

        Dim max As String = words(0), min As String = words(0)

        Dim w As String
        For Each w In words
            If (w.Length > max.Length) Then
                max = w
            End If
            If (w.Length < min.Length) Then
                min = w
            End If
        Next

        Console.WriteLine("The largest word is: {0}", max)
        Console.WriteLine("The smallest word is: {0}", min)

    End Sub

End Module



' run:
' 
' The largest word is: python
' The smallest word Is: c
'

 



answered Mar 21, 2017 by avibootz
edited Sep 14, 2021 by avibootz
0 votes
Imports System
Imports System.Linq

Module WordAnalyzer

    ''' <summary>
    ''' Finds the largest and smallest words in a given string.
    ''' </summary>
    ''' <param name="text">The input string containing words.</param>
    ''' <returns>A named value tuple containing the largest and smallest words.</returns>
    Public Function FindLargestAndSmallestWords(text As String) As (Largest As String, Smallest As String)
        If String.IsNullOrWhiteSpace(text) Then
            Return (String.Empty, String.Empty)
        End If

        ' Split the string by whitespace characters, discarding empty entries
		Dim words As String() = text.Split(New Char() {" "c, environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

        If words.Length = 0 Then
            Return (String.Empty, String.Empty)
        End If

        ' Use LINQ OrderBy/OrderByDescending to find extrema by length
        Dim largest As String = words.OrderByDescending(Function(w) w.Length).First()
        Dim smallest As String = words.OrderBy(Function(w) w.Length).First()

        Return (largest, smallest)
    End Function

    Sub Main()
        Dim s As String = "Visual Basic is a modern, object-oriented programming language"

        ' Destructure the named value tuple returned by the function
        Dim result = FindLargestAndSmallestWords(s)

        Console.WriteLine($"Largest word:  {result.Largest}")
        Console.WriteLine($"Smallest word: {result.Smallest}")
    End Sub

End Module
 
 
' run:
'
' Largest word:  object-oriented
' Smallest word: a
'

 



answered 1 day ago by avibootz
...