Orl213 Orl213 - 2 months ago 6
Vb.net Question

How to copy only numbers from one array to another

I haven't written anything in VB in several years. I am taking a intermediate class and am running into an issue. I am working on an invoice program that is suppose to take the user entered data from a textbox( city state and zip) and use only the zip as the invoice number. I have made an array that stores the user data but I can't figure out how to iterate through it and only write the numeric values to another array. Once that is done I will need to iterate through the second array and write the array contents to a string so it can be displayed as the invoice number. Any help would be greatly appreciated

'the array that holds the user city state and zip

Dim UserZip As String = txtCItyStateZip.Text
Dim UserArray() As Char = UserZip.ToCharArray
Dim ZipArray(4) As Integer

For num As Integer = 0 To UserArray.Length - 1
If IsNumeric(num) Then
ZipArray(num)
num += 1
End If
Next`

Answer

Save zip numbers as array of char and use constructor of type string which takes char array as parameter .

Dim UserZip As String = txtCItyStateZip.Text
Dim UserArray() As Char = UserZip.ToCharArray
Dim ZipChars As New List(Of Char)()

For num As Integer = 0 To UserArray.Length - 1
    Dim character As Char = UserArray(num)
    If IsNumeric(character) Then
        ZipArray.Add(character)
    End If
Next

Dim ZipCode As String = New String(ZipChars.ToArray())

Use List(Of Char) for saving zip's characters, because in cases when zip will contain more then 4 numbers you code will throw exception.

Comments