简体   繁体   中英

How can I parse records from a text file to an array?

here is a snippet of the file,

Year 1
mandatory
COM137,Mathematics for Computing,20,2
COM140,Computer Technologies,1-2,20
COM147,Introduction to databases,1-2,20
Year 2
optional
COM606 ..... etc

I want from this an array that reads

COM317,Mathematics for Computing,20,2,M,Year1

COM140,Computer Technologies,1-2,20,M,Year1

this is the layout of each element in the array that i want, but i have no idea how to do it, so the app reads the document see's year 1 stores that in current year then reads mandatory stores that as M in a variable, then i want to add that to an array, then when it sees year 2 it starts again year 2 added to the array element instead.. this is the what i have attempted so far

  Dim arrModules As String()
    Dim count As Integer = 0
    Dim sr As StreamReader = New StreamReader("datasource.txt")
    Dim line = sr.ReadLine() ' get each line and store it 
    Dim currentYear As Integer
    Dim moduleStats As String = ""
    Dim modArray As String()


    While Not sr.EndOfStream
        If line.Contains("Year") Then
            currentYear = line
        ElseIf line.Contains("mandatory") Then
            moduleStats = "M"
        ElseIf line.Contains("optional") Then
            moduleStats = "O"
        ElseIf line.Contains("COM") Then
            modArray = sr.ReadLine.Split(",")

            MsgBox(modArray)
        End If
        count += 1
        sr.ReadLine()
    End While
    End

// in here is where i am having the problem i don't know how to get all the information i need into one specific array element within an array.. i want to get the year and the module status added to the end of an array element

Copy the result from Split to a new, larger array and add the additional info.

Dim modArray As String() = {"A", "B", "C"}
Dim finalArray As String() = New String(modArray.Length + 1) {}
Array.Copy(modArray, finalArray, modArray.Length)
finalArray(finalArray.Length - 2) = "M"
finalArray(finalArray.Length - 1) = "Year1"

Or you can simply use

ReDim Preserve modArray(modArray.Length+2)
modArray(modArray.Length - 2) = "M"
modArray(modArray.Length - 1) = "Year1"

This being Visual Basic, you could make room for the last two elements this way:

Dim i As Integer = modArray.Length
ReDim Preserve modArray((i - 1) + 2)

modArray(i) = moduleStats
modArray(i + 1) = currentYear.ToString()

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