|
-
Mar 30th, 2006, 11:38 PM
#1
Thread Starter
Member
[RESOLVED] Making Arrays larger
For this question I am using VB.NET 2003.
I know to make an array larger you use the ReDim Preserve "array" command, but I was wondering how to determine if my original array is too small.
If I make an array 50 "blocks" long, and I am reading from a file that has 55 lines, then how do I know that the array is too small and therefore should make it 100 blocks long, etc.
Thanks
-
Mar 30th, 2006, 11:52 PM
#2
Re: Making Arrays larger
The following code doubles the length of the array each time, which is what a collection does with its Capacity. You may choose to grow the array by a fixed amount each time instead.
VB Code:
Dim arr(50 - 1) As String
Dim sr As New IO.StreamReader("C:\MyFile.txt")
Dim linesRead As Integer = 0
Do Until sr.Peek() = -1
If linesRead = arr.Length Then
'We have filled the array so enlarge it.
ReDim Preserve arr(arr.Length * 2 - 1)
End If
arr(linesRead) = sr.ReadLine()
Loop
'Remove unused elements.
ReDim Preserve arr(linesRead - 1)
sr.Close()
You might also look at using a Specialized.StringCollection instead, depending on the circumstances. It is a collection and thus handles the growing and shrinking automatically.
Last edited by jmcilhinney; Mar 30th, 2006 at 11:55 PM.
-
Mar 30th, 2006, 11:56 PM
#3
Re: Making Arrays larger
VB Code:
Dim MyArray(55) As String
Dim tr As StreamReader = New StreamReader("c:\MyFile.txt")
Dim intLines As Integer = UBound(Split(tr.ReadToEnd(), vbNewLine)) + 1
If intLines > UBound(MyArray) Then
ReDim Preserve MyArray(intLines)
End If
tr.Close()
Last edited by jcis; Mar 31st, 2006 at 01:40 AM.
-
Mar 30th, 2006, 11:56 PM
#4
Thread Starter
Member
Re: Making Arrays larger
Thats great! Just what I was looking for.
Thanks again
-
Mar 31st, 2006, 01:12 AM
#5
Re: Making Arrays larger
 Originally Posted by jcis
VB Code:
Dim MyArray(55) As String
Dim tr As StreamReader = New StreamReader("c:\MyFile.txt")
Dim intLines As Integer = UBound(Split(tr.ReadToEnd(), vbNewLine)) + 1
If intLines > UBound(MyArray) Then
ReDim Preserve MyArray(100)
End If
tr.Close()
If you're going to do it that way then you may as well jsut do this:
VB Code:
Dim myArray As String() = System.Text.RegularExpressions.Regex.Split(myStreamReader.ReadToEnd(), Environment.NewLine)
No need to ever specify the size of the array because you aren't creating it explicilty. You can also use the Split Runtime function but I prefer to avoid Runtime functions. I couldn't really say which is more efficient in this case though.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|