Split integer into array VB

11,879

Solution 1

This code is untested:

Dim x As Integer = 987654321
Dim s As String = x.ToString
Dim a(s.Length) As String

For i As Integer = 0 To s.Length - 1
  a(i) = s.Substring(i, 1)
Next i

Solution 2

You could try:

Dim number As Integer = 987654321
Dim strText As String = number.ToString()

Dim charArr() As Char = strText.ToCharArray()

Once the numbers are separated, you can then pull them out from this array and convert them back to numbers if you need to.

Solution 3

Dim number As Integer = 987654321
Dim digits() As Integer = number.ToString().Cast(Of Integer)().ToArray()

Solution 4

Will show any number separated in 3 different message box. You can make a function with the example to better suit your purpose.

Sub GetNumber()
Dim x As Integer, s As String
x = 987
s = LTrim(Str(x))

For i = 1 To Len(s)
    MsgBox Mid(s, i, 1)
Next i
End Sub

Solution 5

I know this is an old question, but here is the most elegant solution I could get to work:

Dim key As Integer = 987654321
Dim digits() As Integer = System.Array.ConvertAll(Of Char, Integer)(key.ToString.ToCharArray, Function(c As Char) Integer.Parse(c.ToString))
Share:
11,879
Filipe Costa
Author by

Filipe Costa

Software developer. www.incentea.pt

Updated on June 23, 2022

Comments

  • Filipe Costa
    Filipe Costa almost 2 years

    Good afternoon,

    How can i split a value and insert it into a array in VB?

    An example:

    The initial value is 987654321.

    Using a for loop i need to insert the value as something like this:

    Position(1) = 9 'The first number from the splited integer

    Position(2) = 8 'The second number from the splited integer

    and so on...

    Thank you.