2

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.

5 Answers 5

2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

1 Comment

Getting an invalid cast exception when calling the .Cast(of Integer)() method.
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.