How to extract and sort numbers from a string containing numbers and text in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

'
'  This program extracts all integer values from a mixed string
'  and sorts them using the language's built‑in list sorting mechanism.
'
'  It demonstrates:
'    - clear separation of concerns using functions
'    - straightforward character parsing
'    - dynamic storage using List(Of Integer)
'    - efficient sorting with List.Sort
'

Module ExtractAndSortNumbers

    '------------------------------------------------------------
    ' Extract all integer values from a mixed string.
    ' The function walks through each character, collects digits,
    ' and converts completed digit sequences into integers.
    '------------------------------------------------------------
    Function ExtractNumbers(input As String) As List(Of Integer)
        Dim numbers As New List(Of Integer)()
        Dim buffer As New System.Text.StringBuilder()

        For Each ch As Char In input
            If Char.IsDigit(ch) Then
                ' accumulate digits
                buffer.Append(ch)
            Else
                ' flush buffer if it contains a number
                If buffer.Length > 0 Then
                    numbers.Add(Integer.Parse(buffer.ToString()))
                    buffer.Clear()
                End If
            End If
        Next

        ' flush trailing number
        If buffer.Length > 0 Then
            numbers.Add(Integer.Parse(buffer.ToString()))
        End If

        Return numbers
    End Function

    '------------------------------------------------------------
    ' Print all numbers in a space‑separated format.
    '------------------------------------------------------------
    Sub PrintNumbers(numbers As List(Of Integer))
        For i As Integer = 0 To numbers.Count - 1
            Console.Write(numbers(i))
            If i < numbers.Count - 1 Then
                Console.Write(" ")
            End If
        Next
        Console.WriteLine()
    End Sub

    '------------------------------------------------------------
    ' Main 
    '------------------------------------------------------------
    Sub Main()
        Dim input As String = "1000withz7 and3 or 99 give42"

        ' extract numbers
        Dim numbers As List(Of Integer) = ExtractNumbers(input)

        ' sort numbers
        numbers.Sort()

        ' display result
        Console.Write("Sorted numbers: ")
        PrintNumbers(numbers)
    End Sub

End Module



'
' run:
'
' Sorted numbers: 3 7 42 99 1000
'

 



answered Aug 12 by avibootz
edited Aug 12 by avibootz
...