开发者

Split integer into array VB

开发者 https://www.devze.com 2023-02-15 16:19 出处:网络
Good afternoon, How can i split a value and inser开发者_如何学编程t it into a array in VB? An example:

Good afternoon,

How can i split a value and inser开发者_如何学编程t 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.


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


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.


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消