Filipe Costa
Filipe Costa

Reputation: 664

Split integer into array VB

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.

Upvotes: 3

Views: 12791

Answers (5)

nickmoriarty
nickmoriarty

Reputation: 1263

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.

Upvotes: 2

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))

Upvotes: 1

just helping
just helping

Reputation: 11

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

Upvotes: 1

Joel Coehoorn
Joel Coehoorn

Reputation: 415735

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

Upvotes: 1

aphoria
aphoria

Reputation: 20189

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

Upvotes: 2

Related Questions