locked
How do you split up lines of files into arrays? RRS feed

  • Question

  • I have a text file (photo attached). On each line is a team number followed by some info on that line, about that team. I would like each line to be split up, by "," and ";", into an array. For example:

    • Line 1 of file = teamOne array with values {"team 1","info","more info","more stuffs"}

    I tried to write this already - with one line in the text file - even without success (attached). Of course I wish for it to work with several lines, but there I really have no clue as to what to do. People have been telling me to use lists, but I do not understand them.

    Module Program
    	Sub Main()
    	      Dim separators() As String = {",", ".", "!", "?", ";", ":", " "}
    	      Dim value As String
    	      Dim words() As String = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
    	      Dim fileline As String
    	      
    	      FileOpen(1, "file.txt", OpenMode.Input)
    			
    	      Do While Not EOF(1)
    		 fileline = LineInput(1)
    		 value(fileline)
    	      Loop
    			
    	      FileClose(1)
    	      
    	      For Each word In words
    	         Console.WriteLine(word)
    	      Next
    	      Console.ReadKey()
    	End Sub
    End Module
    (In console to reduce complexity).

    I hope I made this clear enough. Thanks!

    Saturday, October 28, 2017 10:47 AM

All replies

  • Bobby,

    Per line you'd use something like this:

    Public Class Form1
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            Dim text As String = "team1;info,more,more stuffs"
    
            Dim s() As String = text.Split(New Char() {";"c, ","c}, StringSplitOptions.RemoveEmptyEntries)
    
            Stop
    
        End Sub
    End Class

    You might consider setting up a class to take care of all of this but I don't know enough about your information here.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    • Proposed as answer by Cor Ligthert Saturday, October 28, 2017 11:08 AM
    Saturday, October 28, 2017 11:00 AM
  • I have a text file (photo attached). On each line is a team number followed by some info on that line, about that team. I would like each line to be split up, by "," and ";", into an array. For example:

    • Line 1 of file = teamOne array with values {"team 1","info","more info","more stuffs"}

    For example  :

    List<string> data = "team 1;info,more info,more stuffs".Split(';',',').ToList<string>();

    Saturday, October 28, 2017 11:03 AM
  • I have a text file (photo attached). On each line is a team number followed by some info on that line, about that team. I would like each line to be split up, by "," and ";", into an array. For example:

    • Line 1 of file = teamOne array with values {"team 1","info","more info","more stuffs"}

    For example :

    Dim data As List(Of String) = "team 1;info,more info,more stuffs".Split(";"c, ","c).ToList()

    Saturday, October 28, 2017 11:07 AM
  • Hi,

    I don't understand any of that you put there. I don't know what this does:

    Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    

    I don't understand any of it. Sorry, but I'm no expert like you. I can't even run it.

    I don't know :(

    Saturday, October 28, 2017 11:08 AM
  • Hi,

    I don't understand any of that you put there. I don't know what this does:

    Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load

    I don't understand any of it. Sorry, but I'm no expert like you. I can't even run it.

    I don't know :(

    Please make it obvious who you're talking to.

    That's for a WinForms application. If you're using a console application then focus on the method I showed, not the specifics. Per line split the string based on a new character array (which contains the delimiters).


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, October 28, 2017 11:12 AM
  • Hi,

    I don't understand any of that you put there. I don't know what this does:

    Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load

    I don't understand any of it. Sorry, but I'm no expert like you. I can't even run it.

    I don't know :(

    Be aware that your question is very incomplete. Frank replied to your example while you have all kind of strange separators in your shown code. 

    On the other hand Frank never uses a console template to show samples. The only thing you have to do is remove all your code from your main class without the read key and paste the 2 lines of code from Frank above that. 

    The code from Castorix works the same but that returns not an array but a collection (list)


    Success
    Cor

    Saturday, October 28, 2017 11:13 AM
  • Hi Bobby45800,

    I think Frank L. Smith's post is good, I  add some code to improved his code, maybe there are some code you want to get.

      Private Sub Form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Dim path As String = "D:\test\Test1.txt"
            Dim list As New List(Of String)
    
            Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader(path)
            While Not (reader.Peek() = -1)
                Dim lines As String() = reader.ReadLine().Split(New Char() {";"c, ","c}, StringSplitOptions.RemoveEmptyEntries)
                list.AddRange(lines)
            End While
    
    
            reader.Close()
    
        End Sub

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, October 30, 2017 8:58 AM
  • Give this a try

        Sub Main()
            Dim separators() As Char = {","c, "."c, "!"c, "?"c, ";"c, ":"c, " "c}
            Dim words As New List(Of String)
    
            Dim filelines() As String = IO.File.ReadAllLines("file.txt")
    
            For Each line As String In filelines
                words.AddRange(line.Split(separators, StringSplitOptions.RemoveEmptyEntries))
            Next
    
            For Each word As String In words
                Console.WriteLine(word)
            Next
            Console.ReadKey()
        End Sub
    


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it" - MSDN User JohnWein

    Monday, October 30, 2017 10:59 AM
  • Here is another way to attack this.

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim itemList As New List(Of Item)
            Using MyReader As New FileIO.TextFieldParser(IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFile1.txt"))
    
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.Delimiters = New String() {";", ","}
    
                Dim currentRow As String()
    
                While Not MyReader.EndOfData
                    Try
                        currentRow = MyReader.ReadFields()
                        itemList.Add(New Item With {.Name = currentRow(0), .Field1 = currentRow(1), .Field2 = currentRow(2)})
    
                    Catch ex As FileIO.MalformedLineException
                        Console.WriteLine("Line " & ex.Message & " is invalid.  Skipping")
                    End Try
                End While
            End Using
    
            itemList.ForEach(Sub(item) Console.WriteLine(item.ToString))
    
        End Sub
    End Class
    Public Class Item
        Public Property Name As String
        Public Property Field1 As String
        Public Property Field2 As String
        Public Overrides Function ToString() As String
            Return $"{Name}, {Field1}, {Field2}"
        End Function
    End Class
    

    The text file

    Team 1;A1,B1
    Team 2;C1,D1
    Team 3;E1,F1

    Output from above code in the IDE output window


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, October 30, 2017 12:41 PM