Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

How to sort a string in the order: lowercase letters - uppercase letters - odd digits - even digits in VB.NET

1 Answer

0 votes
Imports System

Public Class SortAlphaNumeric

    '
    ' We want to sort characters in this strict order:
    ' 1. lowercase letters   (a–z)
    ' 2. uppercase letters   (A–Z)
    ' 3. odd digits          (1,3,5,7,9)
    ' 4. even digits         (0,2,4,6,8)
    '
    ' Strategy:
    ' ---------
    ' Assign each character a "category rank" and sort by:
    '     (category rank, natural character order)
    '
    ' VB.NET allows custom sorting using Array.Sort with a Comparison(Of T).
    '

    ' Returns category rank for sorting.
    ' Lower rank = comes earlier.
    Shared Function Category(c As Char) As Integer
        If c >= "a"c AndAlso c <= "z"c Then Return 0   ' lowercase
        If c >= "A"c AndAlso c <= "Z"c Then Return 1   ' uppercase

        If Char.IsDigit(c) Then
            Dim d As Integer = Convert.ToInt32(c) - Convert.ToInt32("0"c)
            If d Mod 2 = 1 Then
                Return 2   ' odd digits
            Else
                Return 3   ' even digits
            End If
        End If

        Return 4 ' fallback (should not happen for alphanumeric input)
    End Function

    ' Custom comparator for sorting characters
    Shared Function CompareChars(a As Char, b As Char) As Integer
        Dim ca As Integer = Category(a)
        Dim cb As Integer = Category(b)

        If ca <> cb Then
            Return ca - cb   ' sort by category first
        End If

        Return Convert.ToInt32(a) - Convert.ToInt32(b)   ' tie-breaker: natural order
    End Function

    Public Shared Sub Main()

        Dim s As String = "a2B3cD8f1Z0"

        ' Convert string to array of chars
        Dim arr() As Char = s.ToCharArray()

        ' Sort using custom comparator
        Array.Sort(arr, Function(a, b) CompareChars(a, b))

        ' Build result string
        Dim result As String = New String(arr)

        Console.WriteLine("Sorted result: " & result)
    End Sub

End Class

			
'
' run:
'
' Sorted result: acfBDZ13028
'

 



answered Jul 14 by avibootz

Related questions

...