简体   繁体   中英

VB.net Split string intro multiple variables

For a school project we need to make a BoardGame, Now I have made a list of location for the NPC.

These locations are stored in a txt file named player2.txt, as followed http://pastebin.com/ZhbSvjSt

Im using the following the code to read them from the file. http://pastebin.com/UjLSeWrQ

Dim TurnP2 As String = IO.File.ReadAllLines(".\player2.txt")(Turn)
Dim source As String = TurnP2
Dim result() As String = Split(source, ",")

But now I'm stuck, I have no clue how to splits these 3 numbers into variable. For example Take the first row 1,1,5

I need it to place these numbers in the following variables:

CoX = 1
CoY = 1
CoZ = 5

Can anyone help me further?

Also sorry for using pastebin, but I got a strange error while trying to post.

Regards Jurre

I would create a Class:

   Private Class Coords
        Public coordX As Integer
        Public coordY As Integer
        Public coordz As Integer
    End Class

And then I would fill a list:

    Dim source As String() = System.IO.File.ReadAllLines(".\player2.txt")
    Dim ListCoords = New List(Of Coords)

    For Each Val As String In source

        Dim s As String() = Val.Split(",")

        ListCoords.Add(New Coords With {.coordX = s(0).ToString, _
                             .coordY = s(1).ToString, _
                             .coordz = s(2).ToString})

    Next

You will have a list of loaded coordinates:

在此处输入图片说明

You have multiple lines, so are CoX , CoY , CoZ arrays?

You can use a loop to initialize them. Presuming always valid data:

Dim TurnP2 As String() = IO.File.ReadAllLines(".\player2.txt")
Dim CosX(TurnP2.Length - 1) As Int32
Dim CosY(TurnP2.Length - 1) As Int32
Dim CosZ(TurnP2.Length - 1) As Int32
For i As Int32 = 0 To TurnP2.Length - 1
    Dim values = TurnP2(i).Split(","c)
    CosX(i) = Int32.Parse(values(0))
    CosY(i) = Int32.Parse(values(1))
    CosZ(i) = Int32.Parse(values(2))
Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM