Results 1 to 4 of 4

Thread: [RESOLVED] Get a two dimensional array from a string

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2008
    Posts
    470

    Resolved [RESOLVED] Get a two dimensional array from a string

    Hi I want to convert a stringbuilder to a matrix.
    sb.Append("1,1,2,2,0,0,a,b,c,d,1,1,2,2,0,1,e,f,g,h,1,1,2,2,0,1,x,y,x,z");

    The expected matrix is
    Code:
    1,1,2,2,0,0,a,b,c,d
    1,1,2,2,0,1,e,f,g,h
    1,1,2,2,0,1,x,y,x,z
    Suppose the matrix has k rows, here k=3.
    Thanks for help.

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,104

    Re: Get a two dimensional array from a string

    Does each row always have 10 columns?
    My usual boring signature: Nothing

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2008
    Posts
    470

    Re: Get a two dimensional array from a string

    Each row has fixed columns.

  4. #4
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Get a two dimensional array from a string

    May not be elegant but it works off a StringBuilder.ToString method. I did a List(Of String), you can tweak it to an array.

    Code:
    Private Sub Form1_Load() Handles MyBase.Load
       Dim sb As New System.Text.StringBuilder
       sb.Append("1,1,2,2,0,0,a,b,c,d,1,1,2,2,0,1,e,f,g,h,1,1,2,2,0,1,x,y,x,z")
    
       Dim Result = sb.ToString.BreakApart
       If Result.Count > 0 Then
          For Each item In Result
             Console.WriteLine("[{0}]", item)
          Next
       End If
    End Sub
    Place in code module
    Code:
    <Runtime.CompilerServices.Extension()> _
    Public Function BreakApart(ByVal Values As String) As List(Of String)
       Dim Items As New List(Of String)
       Dim Count As Integer = Values.Split(",".ToCharArray).Length \ 10
    
       If Count > 0 Then
          Items.Add(Values.Substring(0, 19))
          If Count > 1 Then
             For x As Integer = 1 To Count - 1
                Items.Add(Values.Substring(x * 20, 19))
             Next
          End If
       End If
    
       Return Items
    
    End Function

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width