none
exclude null/empty values in an array when sorting it visual basic RRS feed

  • Question

  • So my problem is the following. For an exercise for school I have to make a program where the user has to fill in a vegetable. When the array is full, the capacity is doubled. The vegetables have to be ordened.

    What I can't fix: the null values mess up the sorting and I have this solution but after 5 values the result is fucked up because there is more than 1 null value when the capacity is doubled from 4 to 8.

    How can I make sure that the null value is at the end of the array when sorted or that it is ignored?

    Module Vegetable
        Sub Main()
            Dim vegetables As String() = {"lettuce", "leek"}
            Dim amount As Integer = 2
            Do
                Console.WriteLine("Vegetables (" & amount & "/" & vegetables.Length & ") : ")
                Array.Sort(vegetables)
                For index As Integer = 0 To vegetables.Length - 1
                    If vegetables(index) = "" Then
                        vegetables(index) = vegetables(vegetables.Length - 1)
    
                    Else
                        Console.WriteLine("- " & vegetables(index))
                    End If
    
    
                Next
                Console.WriteLine()
    
                Console.Write("Next vegetable? : ")
    
                Dim newVegetable As String = Console.ReadLine()
    
                Console.WriteLine()
                If vegetables.Length = amount Then
                    ReDim Preserve vegetables((amount * 2) - 1)
                End If
    
                vegetables(amount) = newVegetable
                Array.Sort(vegetables)
                amount += 1
            Loop
        End Sub
    End Module

    Sunday, November 3, 2013 10:48 AM

All replies

  • I initially passed over this question because this is a Visual Basic for Applications (VBA) forum and I don't code in the language you have used. However, as the question has been here for some time now without an answer, I thought that I might give you a pointer that might help.

    Before invoking the sort, you should be able to iterate through the array and replace null values with chr(255) which will force it to the end during a sort. After sorting iterate through the array again and replace the chr(255) with a null.


    Regards, OssieMac

    Monday, November 4, 2013 1:02 AM